活跃农民
- 积分
- 431
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-8-4
- 最后登录
- 1970-1-1
|
5.15 做题
78. Subsets. There are two ways to construct the recursion tree of this problem. The solution in discussion construct a k-nary tree, while mine is a binary tree. The number of levels of my recursion tree is equal to the number of elements in given array. And each node has two child nodes in recursion tree. So we need call recursion function twice, one is adding current element while the other is not. Then we continue to the next elements in given array. I think the design of signature is really important.
90. Subsets II. This is the same problem as the last one. The only two differences are we need to add a HashSet and sort the given array before we do DFS, in order to avoid the repetition. It really confuses me why to sort first?
77. Combinations. Still very similar with the Subset problem. The only difference is in base case. Since this is the combinations problem, we must make sure all results have length exactly equal to given K. And we use this as the base case.
39. Combination Sum. There are two important points in this problem. First, we need sort the given candidates array first. Since in recursion function, we scan from left to right, and the elements in left-side will be first inserted into the solution. I think all following discussion are based on this large element. If the elements in left-side are too large, the target in following recursion calls will be too small. So we just need to put smaller elements in left so we still have target values in following recursion functions call. The other thing is, how do we call the recursion function? In this case, we are allowed to use elements repeatedly to sum up. So we call recursion function with the same index, rather than index + 1, which is different from the last few dfs problems. However, if we call recursion function like that, there will be stackoverflow since there is no difference in recursion function. We need to change the target value, just like what we do in Path Sum problem. So the base case is when target value is equal to Zero, we will get one result. Besides, in the loop condition, we need add a condition, the one that the current target should always be larger than current candidate elements. Since every time we call recursion function, we will minus target by current candidate elements. And since the base case is target equal to Zero. If we don't add the condition that target should be always larger than current element, in following recursion functions call the target will be negative, will continually decrease. And it will never meet the base case. In this case, the stackoverflow will happen.
40. Combination Sum II. 和前面那个题差不多一样,要注意的就是这个题目的given candidates array allow duplicates while in the solution, both solu and res, the duplicates are not allowed. So I use a HashSet as res, and the recursive rule is a bit different. |
|