40. Combination Sum II

来源:互联网 发布:知耻而后勇是什么意思 编辑:程序博客网 时间:2024/06/06 14:25

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

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]]

先将数组排序,再用回溯法


public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> set=new LinkedList<>();        LinkedList<Integer> list=new LinkedList<>();        Arrays.sort(candidates);        helper(candidates,target,0,set,list);        return new LinkedList<>(set);    }    public void helper(int[] nums,int k,int index,List<List<Integer>> set,LinkedList<Integer> list){        if(k==0){            set.add(new LinkedList<>(list));            return;        }        if(k<0)            return;        for(int i=index;i<nums.length;i++){            if(i>index&&nums[i-1]==nums[i]) continue;            list.add(nums[i]);            helper(nums,k-nums[i],i+1,set,list);            list.removeLast();        }    }}


0 0