Combination Sum II

来源:互联网 发布:小蜜蜂软件官方网 编辑:程序博客网 时间:2024/06/04 00:43

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC 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 target8,
A solution set is:

[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]
思路:一次只能算一次,index要从下一个开始,还要去重,因为[1,1,2,5] 如果不去重,会出现[1,2,5] [1,2,5] 两次,所以要去重。

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> lists = new ArrayList<List<Integer>>();        if(candidates == null || candidates.length == 0){            return lists;        }        List<Integer> list = new ArrayList<Integer>();        Arrays.sort(candidates);        collect(candidates, lists, list, target, 0 , 0);        return lists;    }        public void collect(int[] candidates, List<List<Integer>> lists, List<Integer> list, int target, int sum, int index){        if(sum > target) return;        if(sum == target){            lists.add(new ArrayList<Integer>(list));            return;        }        for(int i=index; i<candidates.length; i++){            if(i>index && candidates[i] == candidates[i-1]){                continue;            }            sum += candidates[i];            list.add(candidates[i]);            collect(candidates, lists, list, target, sum, i+1);            list.remove(list.size()-1);            sum -= candidates[i];        }    }}



0 0
原创粉丝点击