Algorithms note 40. Combination Sum via II 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++; } } } }

Time Complexity Analysis: sorting O (nlgn) + n layer recursive, for each node a worst O (n) traversal, the shape is not Balance recursive tree, the analysis is not very good, approximately O (2 ^ n ) reference analysis: https: //www.1point3acres.com/bbs/thread-117602-1-1.html

Space complexity: recursive and spatial tree path, each node of all nodes and additional space is not used, so this part of O (height) = O (n), the answer to save space complexity is O ( n) (uncertainty) overall is O (n)

Guess you like

Origin www.cnblogs.com/zg1005/p/11876390.html