• 组合数


    问题: 给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 ;
        }
    }

  • 相关阅读:
    在controller间分享数据(第一种办法)
    AngularJS之Factory vs Service vs Provider
    directive和controller如何通信
    AngularJS 之Services讲解
    AngularJS心得体会
    int 和Integer
    2019天梯赛练习题(L2专项练习)
    2019天梯赛练习题(L1专项练习)
    Hash冲突的几种解决方法
    HashMap
  • 原文地址:https://www.cnblogs.com/energy1010/p/6867391.html
Copyright © 2020-2023  润新知