combination sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

 

跟上题combination sum I 一样,回溯。

 这一题相比combination sum I,做了两点修改,1、数组中每个元素只能被使用一次;2、数组中有重复元素。针对1,每次添加list从下一个元素开始(i+1);针对2,每次遍历的时候,跳过重复的元素。

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result=new ArrayList<List<Integer>>();
        if(candidates==null||candidates.length==0) return result;
        Arrays.sort(candidates);
        backtracking(result,new ArrayList<Integer>(),candidates,target,0,0);
        return result;
    }
    
    public void backtracking(List<List<Integer>> result,List<Integer> list,int[] nums,int target,int sum,int index){
        if(sum>target) return ;
        if(sum==target){
            result.add(new ArrayList<Integer>(list));
            return ;
        }
        if(index>nums.length-1) return ;
        /*
        这一题相比combination sum I,做了两点修改,1、数组中每个元素只能被使用一次;2、数组中有重复元素。针对1,每次添加list从下一个元素开始(i+1);针对2,每次遍历的时候,跳过重复的元素。
        */
        for(int i=index;i<nums.length;i++){
            //每次遍历时,跳过重复元素,这样就不会出现重复的两个list
            if(i>index&&nums[i]==nums[i-1]) continue;  
            list.add(nums[i]);
            backtracking(result,list,nums,target,sum+nums[i],i+1);
            list.remove(list.size()-1);
        }
    }
}

 

posted on 2017-12-26 13:17  夜的第八章  阅读(158)  评论(0)    收藏  举报

导航