LeetCode-40. Combination Sum II

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

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

元素不可重复

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        List<Integer> curL = new ArrayList<>();
        Arrays.sort(candidates);
        help(re,curL,candidates,target,0);
        return re;
    }
        private void help(List<List<Integer>> re,List<Integer> cur,int[] arr,int value,int index){
        if(value==0){
            List<Integer> l=new ArrayList<>(cur);
            re.add(l);
            return;
        }
        else{
            for(int i=index;i<arr.length&&arr[i]<=value;i++){
                if(i>index&&arr[i]==arr[i-1]){
                    continue;
                }              
                cur.add(arr[i]);
                help(re,cur,arr,value-arr[i],i+1);
                cur.remove(cur.size()-1);
            }
        }
    }

 

相关题

LeetCode 39.Combination Sum https://www.cnblogs.com/zhacai/p/11205292.html

posted @ 2019-07-18 10:01  月半榨菜  阅读(105)  评论(0编辑  收藏  举报