39. Combination Sum

2018-01-08  本文已影响0人  ThereThere_0d70

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<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);//排序
        List<List<Integer>> result = new ArrayList<>();
        if(candidates.length == 0||target < candidates[0])
            return result;
        List<Integer> com = new ArrayList<>();
        combine(candidates,com,target,result,0);
        return result;
    }
    public void combine(int[] candidates,List<Integer> com,int target,List<List<Integer>> result,int begin){
        if(target<candidates[begin]) return;//全是正数的情况下,说明已经不存在可行解了
        
        for(int i = begin;i < candidates.length;i++){//i从begin开始,是为了避免找到重复解
            if(target==candidates[i]){//找到可行解
                com.add(candidates[i]);
                result.add(new ArrayList<>(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);
           
        }
       
    }
}
上一篇下一篇

猜你喜欢

热点阅读