zoukankan      html  css  js  c++  java
  • 算法笔记 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)

  • 相关阅读:
    马士兵Java学习之路
    @Component, @Repository, @Service的区别
    编译器警告:CGContextSaveGState: invalid context 0x0
    Other Linker Flags到底是什么
    Xcode常用快捷键(持续更新-20160811)
    iOS应用文件夹
    iOS compare 字符串比较
    去掉UITableView多余的空白行分割线
    iOS 查询数组中的对象
    UISearchController使用
  • 原文地址:https://www.cnblogs.com/zg1005/p/11876390.html
Copyright © 2011-2022 走看看