问题描述
https://leetcode.com/problems/combination-sum-ii/
问题解惑
这题还要回头理解,这次先放过去了,大体和39题差不多,还有一些细节处理。
代码
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
//corner case
if(candidates == null || candidates.length <= 0 || target < 0) return res;
Arrays.sort(candidates);
helper(res, new ArrayList<>(), candidates, target, 0);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start){
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(list));
return;
}
for(int i = start; i < candidates.length; i++){
if(i != start && candidates[i - 1] == candidates[i]) continue;
list.add(candidates[i]);
helper(res, list, candidates, target - candidates[i], i + 1);
list.remove(list.size() - 1);
}
}
}
复杂度分析
- 时间复杂度:O(2^n)
- 空间复杂度:O(n)