问题描述:
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]
原问题链接:https://leetcode.com/problems/combination-sum-ii/
问题分析
其实这个问题和前面那个问题差不多。我们同样可以用递归的方式来解决。在前面的问题里因为数组里的元素可以取多次,我们下一次的递归的时候可以继续从i这个点开始。而这里的话则必须从下一个开始。因此只是对上述问题的解法做一个很小的修改就可以适配这个问题了。
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
Arrays.sort(num);
recurse(new ArrayList<Integer>(), target, num, 0, ret);
return ret;
}
private void recurse(List<Integer> list, int target, int[] candidates, int index, List<List<Integer>> ret) {
if (target == 0) {
if(!ret.contains(list))
ret.add(list);
return;
}
for(int i = index; i < candidates.length; i++) {
int newTarget = target - candidates[i];
if(newTarget >= 0) {
List<Integer> copy = new ArrayList<Integer>(list);
copy.add(candidates[i]);
recurse(copy, newTarget, candidates, i + 1, ret);
} else
break;
}
}
}
上述代码其实就是一个深度优先遍历方法的一个实现。只是在一般的深度优先遍历,如果递归的过程是共用同一套数据结构的话需要将原来设置的值给恢复。而这里每次都是在下一个递归的时候拷贝一个新的数组,所以不需要这一步了。不过这种频繁的数组拷贝也使得程序执行的性能稍微慢了一些。我们也可以根据需要做一些修改。