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 toT.

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] 

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    	Arrays.sort(candidates);
        List<List<Integer>> total = new ArrayList<List<Integer>>();
        List<Integer> l = new ArrayList<Integer>();
        total.add(l);
        return solve(total, candidates, target, 0);
    }

	private List<List<Integer>> solve(List<List<Integer>> total,
			int[] candidates, int target, int pos) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		if (target == 0) {
		    for(List<Integer> l : total) {
                List<Integer> nl = new ArrayList<Integer>(l);
                list.add(nl);
            }
			return list;
		}
		for (int i = pos; i < candidates.length; i++) {
			if (candidates[i] > target) {
				break;
			}
			if (i==pos || candidates[i]!=candidates[i-1]) {
				for (List<Integer> l : total) {
					l.add(candidates[i]);
				}
    			list.addAll(solve(total, candidates, target-candidates[i], i+1));
    			for (List<Integer> l : total) {
    				l.remove(l.size()-1);
    			}
			}
		}
		return list;
	}
   
}

 

你可能感兴趣的:(com)