Combination Sum II

来源:互联网 发布:合并数组js,不要重复的 编辑:程序博客网 时间:2024/05/16 14:24

Q:

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 


Solution:

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


0 0