下面将遇到的可以用递归求解的问题归纳于此
1. Combination
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
【思路】递归
1.用一临时数组solution存储元素, 其大小应为k
2 base case , solution长度为k,并弹出最后元素
3 else 继续向solution push元素
注意:需要引用传参
2. Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
【思路】 递归, 类似于上一题
base case: solution中元素之和sum为target
if sum值大于target 直接返回,并弹出最后元素
else 从candidate numbers 中继续选出元素加到solution中,同时用sum记录当前和值
注意:
1.结果中元素应保持non-descending order, 应先排序
2. 结果可以包含重复元素,递归中直接传level值就可以了,和上一题的不同.
3.Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
【思路】 与上一题类似,不同之处在于不能重复添加candidated中的元素