zoukankan      html  css  js  c++  java
  • 组合数

    问题: 给n个不同的正整数, 取m个数使得和为sum, 其中任意数可以重复取多次

    例如:set [2, 3, 6, 7] and target 7, 结果有[7] ,[2,2,3] 

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidate, int sum){       
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            //corner

            //core
            List<Integer> path = new ArrayList<>();

            Arrays.sort(candidate);

            helper(res, path, candidate, sum, 0);        //start from position = 0

            return res;
        }

        public void helper(List<List<Integer>> res, List<Integer> path, int[] candidate, int sum, int position){
            //base
            if ( sum == 0 ){                                   
                res.add(new ArrayList<Integer>(path));
                return ;                                       
            }

            //current
            for ( int i = position; i < candidate.length && sum >= candidate[i]; i++ ){   
                path.add(candidate[i]);
                //next: pass down remaining 'sum', and afterwards 'start position'
                helper(res, path, candidate, sum - candidate[i], i);       
                path.remove(path.size() - 1);
            }

            return ;
        }
    }

  • 相关阅读:
    javascript 闭包与函数变量作用域
    javaScript for循环
    node-inspector调试node项目
    nodejs async异步常用函数总结
    nodejs安装配置新手篇
    requirejs笔记
    使用nodejs中httpProxy代理时候出现404异常
    Bluebird-Collections
    Bluebird-Core API (三)
    Bluebird-Core API(二)
  • 原文地址:https://www.cnblogs.com/energy1010/p/6867391.html
Copyright © 2011-2022 走看看