题目链接:https://leetcode.com/problems/combination-sum/
题目:
C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
same repeated number may be chosen from C
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.
2,3,6,7
and target 7
,
A solution set is:
[7]
[2, 2, 3]
思路:
允许重复,但选择的数的序列必须是有序的。
算法:
int cl[] = null;
List<List<Integer>> iLists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
int target = 0;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
this.cl = candidates;
this.target = target;
dspCombination(0, 0);
return iLists;
}
private void dspCombination(int sum, int level) {
if (sum == target) {
iLists.add(new ArrayList<Integer>(list));
return;
} else if (sum > target) {
return;
} else {
//类似于迷宫问题
for (int i = level; i < cl.length; i++) { //i=level保证了下一步不会选择[level]之前的数,即保证了是有序的
sum += cl[i];
list.add(cl[i]);
dspCombination(sum, i); //没有用dspCombination(sum,i+1)给了当前cl[i]再次驻留机会,即允许重复
list.remove(list.size() - 1);
sum -= cl[i];
}
}
}