组合数

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

原文地址:https://www.cnblogs.com/energy1010/p/6867391.html