算法笔记 40. Combination Sum II via Java

class Solution {
    // using backtracking to build solution set;
    // traverse through the candidates list and try using each element as start point for building solution
public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); // solution set, in which are List<Integer> build = new ArrayList<>(); // partial solution Arrays.sort(candidates); helper(candidates, 0, build, res, target); return res; } private void helper(int[] candidates, int idx, List<Integer> build, List<List<Integer>> res, int target){ if(target==0){ List<Integer> toAdd = new ArrayList<>(build); res.add(toAdd); return; } for(int i = idx; i<candidates.length; i++){ if(candidates[i]<=target){ build.add(candidates[i]); helper(candidates, i+1, build, res, target-candidates[i]); build.remove(build.size()-1); } while(i<candidates.length-1 && candidates[i]==candidates[i+1]){ i++; } } } }

时间复杂度分析:排序O(nlgn) + n层递归,每个结点内最坏进行一个O(n)的遍历,递归树的形状不balance,不是很好分析,近似为O(2^n) 参考分析:https://www.1point3acres.com/bbs/thread-117602-1-1.html

空间复杂度:递归树上下一条路径中所有节点的空间和,每层结点中并没有用到额外空间,所以这部分时O(height)=O(n),保存答案空间复杂度为O(n)(不确定)总体为O(n)

猜你喜欢

转载自www.cnblogs.com/zg1005/p/11876390.html