LeetCode Learning 8
来源:互联网 发布:淘宝直通车助手 编辑:程序博客网 时间:2024/06/03 20:02
337. House Robber III
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
还是House Robber,这次从数组变成了二叉树,类似的,也是不能选择相邻的2个节点。由于是树状结构,需要使用递归方法,对每个节点保存2个值包含此节点的最大和,以及不包含此节点的最大和res[1]以及res[0]。对root,root的res[1]等于root->left的res[0]+root->right的res[0]+root的值。而res[0]则等于root->left的max(res[0],res[1]) + root->的max(res[0],res[1])。代码如下:int rob(TreeNode* root) { vector<int> res = dfs(root); return max(res[0], res[1]); } vector<int> dfs(TreeNode *root) { if (!root) return vector<int>(2, 0); vector<int> left = dfs(root->left); vector<int> right = dfs(root->right); vector<int> res(2, 0); res[0] = max(left[0], left[1]) + max(right[0], right[1]); res[1] = left[0] + right[0] + root->val; return res; }
377. Combination Sum IV
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
题意为给出一组正整数与一个目标正整数,求出所有可能的数组中的正整数组合成目标的组合数。依然可以使用动态规划,转移方程中需要加入目标减去数组中每个数的状态。即dp[i]=Σdp[i-nums[k]]。设数组中整数数目为m,目标大小为n,这样的话复杂度会是O(mn)。
最终代码如下:
class Solution {public: int combinationSum4(vector<int>& nums, int target) { vector<int> dp(target + 1); dp[0] = 1; for (int i = 1; i <= target; ++i) { for (int j=0;j<nums.size();j++) { if (i >= nums[j]) dp[i] += dp[i - nums[j]]; } } return dp.back(); }};
- LeetCode Learning 8
- LeetCode Learning 1
- LeetCode Learning 2
- LeetCode Learning 3
- LeetCode Learning 4
- LeetCode Learning 5
- LeetCode Learning 6
- LeetCode Learning 7
- Learning python 系列8
- learning 09-8-14
- learning opencv 3-8
- CodingNet - Learning - 8
- Learning
- learning
- learning
- learning
- learning
- learning
- Android学习之路--四大组件--ContentProvider
- Android WebView上传图片(base64)到H5(JS)
- Java并发之共享受限资源
- LeetCode Learning 7
- java 中文件的读取File、以及相对路径的问题
- LeetCode Learning 8
- 有关UITableViewCell高度计算
- R语言常用命令
- 20161227 spring quartz 定时调度任务 服务 null pointer Exception 解决办法
- 利用 Console 来学习、调试JavaScript
- EditText输入长度的监听
- c语言二叉树创建及遍历
- 17 - 01 - 08 POJ 1555
- 团灭Windows进程通信(六)——最常用到命名管道