Combination Sum(数字组合)

问题

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Notice
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
Example
Given candidate set [2,3,6,7] and target 7, a solution set is:
[7]
[2, 2, 3]

分析

和组合的思路类似,也需要注意组合中的问题,请参阅 组合
另外还需要注意,当有重复元素时需要考虑去重的问题。所以在递归时需要做前一个元素的比较,如果相同就跳过。

代码

    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public List> combinationSum(int[] candidates, int target) {
        // write your code here
        List> res=new ArrayList();
        LinkedList temp=new LinkedList();
        Arrays.sort(candidates);
        tree(candidates,res,temp,target,0);
        return res;
    }
    private void tree(int[] candidates,List> res, LinkedList temp,int target,int index){
        for(int i=index;iindex&&a==candidates[i-1]){
                continue;
            }
            temp.add(a);
            if(a==target){
                res.add(new ArrayList(temp));
            }else if(a

你可能感兴趣的:(Combination Sum(数字组合))