39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) 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.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

class Solution {
    public List> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);//排序
        List> result = new ArrayList<>();
        if(candidates.length == 0||target < candidates[0])
            return result;
        List com = new ArrayList<>();
        combine(candidates,com,target,result,0);
        return result;
    }
    public void combine(int[] candidates,List com,int target,List> result,int begin){
        if(target(com));
                com.remove(com.size()-1);//每次添加一个元素后,无论是不是可行,都要把这个元素再去掉,因为在现有的com里再加入其他元素也可能是可行解
                return;
            }
            com.add(candidates[i]);//把元素加入com,在此情况下,调用combine计算是否可以继续添加元素得到可行解
            combine(candidates,com,target-candidates[i],result,i);
            com.remove(com.size()-1);
           
        }
       
    }
}

你可能感兴趣的:(39. Combination Sum)