题目:
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]
思路:
每个数字只能出现一次了,所以递归时直接定位到下一个元素。
package sum; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CombinationSumII { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> record = new ArrayList<Integer>(); combine(candidates, 0, candidates.length, res, record, target); return res; } private void combine(int[] nums, int start, int end, List<List<Integer>> res, List<Integer> record, int target) { for (int i = start; i < end; ++i) { List<Integer> newRecord = new ArrayList<Integer>(record); newRecord.add(nums[i]); int sum = sum(newRecord); int rem = target - sum; if (rem == 0) { res.add(newRecord); } else if (rem > 0 && rem >= nums[i]) { combine(nums, i + 1, end, res, newRecord, target); } else if (rem < 0) { break; } while (i + 1 < end && nums[i + 1] == nums[i]) ++i; } } private int sum(List<Integer> record) { int sum = 0; for (int i : record) sum += i; return sum; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = { 10,1,2,7,6,1,5 }; CombinationSumII c = new CombinationSumII(); List<List<Integer>> res = c.combinationSum2(nums, 8); for (List<Integer> l : res) { for (int i : l) System.out.print(i + " "); System.out.println(); } } }