问题描述
**题目要求:**见上一题
解题思路
跟上一题的思路基本一样,只不过这题的条件变成每个元素只能出现一次了,只需要微调上一题的解法即可。
代码实现
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList();
List<Integer> tmplist = new ArrayList();
Arrays.sort(candidates);
backtrack(res, tmplist, candidates, target, 0);
return res;
}
public void backtrack(List<List<Integer>> res, List<Integer> tmplist, int[] candidates, int target, int start) {
if(target < 0) return;
else if(target == 0) {
res.add(new ArrayList(tmplist));
} else {
for(int i = start; i < candidates.length; i++) {
tmplist.add(candidates[i]);
//因为一个元素只能出现一次,所以start的位置变成了i+1即可
backtrack(res,tmplist,candidates,target-candidates[i],i+1);
tmplist.remove(tmplist.size()-1);
//这一步是为了去除结果集合中的重复元素,例如每次判断完了1开头的所有解之后,其他1开头的待检测集合就可以直接排除了
while(i<candidates.length-1&&candidates[i] == candidates[i+1])
i++;
}
}
}
复杂度分析:
跟上一题一样的分析也适用,但是这一题不会出现同意元素多次使用,所以树的深度最大就是n即可
所以时间复杂度是O(nn),空间复杂度是O(n*k),其中k代表符合条件的解的个数