试题
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
INPUT: candidates in a = [2,3,5], = target. 8,
A IS SET Solution:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
code is
clearly substantially dp greedy and do not consider, then the rest is traversed. How to be noted that the point is to avoid the [223] and [322] This same set but different sort of situation. It can be considered when using the front when a number of the number can not be used.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> out = new ArrayList<List<Integer>>();
findAll(candidates, target, out, new ArrayList<Integer>(), 0, 0);
return out;
}
// sum用来统计当前遍历的求和,repeat用来记录当前使用到的temp里的最后一个数的index
public void findAll(int[] candidates, int target, List<List<Integer>> out, ArrayList<Integer> temp, int sum, int repeat){
if(sum == target){
out.add((ArrayList)temp.clone());
return;
}
// 为了保证我们不会出现相同集合但是排序不同的情况,我们采用每次尽可能把当前数都探索完。比如repeat = 0,此时index为0的数应该使用了多次,那么我们可以继续使用下去,或者是不再考虑index=0的数,而是开始考虑index=1的数。
for(int i = repeat; i < candidates.length; i++){
int num = candidates[i];
if(sum + num <= target){
temp.add(num);
findAll(candidates, target, out, temp, sum+num, i);
temp.remove(temp.size()-1);
}
}
return;
}
}