Combination Sum

这个题和permutation以及subset一样, 也属于排列组合问题, 用recursive做。 这种题的时间消耗都是指数级别的

public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(candidates.length == 0 || candidates == null){
            return result;
        }
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        combinationSumHelper(result, list, candidates, target, 0);
        return result;
    }
    
    private void combinationSumHelper(List<List<Integer>> result, 
                                      List<Integer> list,
                                      int[] candidates, 
                                      int target,
                                      int pos){
        if(target == 0){
            result.add(new ArrayList<Integer>(list));  
        }
        
        for(int i = pos; i < candidates.length; i++){
            if(candidates[i] > target){
                break;
            } 
            
            if( i > pos && candidates[i] == candidates[i-1]){
                continue;
            }
            
            list.add(candidates[i]);
            combinationSumHelper(result, list, candidates, target-candidates[i], i);
            list.remove(list.size() -1);
        }
    }
}

注意for loop里面的第二个if语句是要除去重复的数列,例如{2,2,3,6,7} target 7, 第二个2不需要再次考虑,因为作用和第一个相同,需要注意的是这个时候还是需要继续loop,所以是continue,但如果是candidate[i]>target, 就没有必要继续寻找,break就可以了

posted on 2016-08-18 07:56  codingEskimo  阅读(117)  评论(0编辑  收藏  举报

导航