Java [Leetcode 40]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 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 (a1, a2, … , 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] 

解题思路:

跟前一个类似,不过每次选好当前元素后,就直接选下一个位置的元素了。并且在每次选元素之前,保证这次的元素与上次的元素不重合。

代码如下:

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

	public void getResult(List<List<Integer>> result,
			List<Integer> current, int[] candiates, int target, int start) {
		if (target > 0) {
			for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
				if (i > start && candiates[i] == candiates[i - 1])
					continue;
				current.add(candiates[i]);
				getResult(result, current, candiates, target - candiates[i],
						i + 1);
				current.remove(current.size() - 1);
			}
		} else if (target == 0) {
			result.add(new ArrayList<Integer>(current));
		}
	}
}