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.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]
题目标签:Array
这道题目和前面那一题本质一摸一样,不同之处是,这题每一个数字只能用一次,之前那题可以无限用;这一题给的array里有重复的,之前那题没有。所以只要之前那题做了,稍微改动一下就可以了。把递归下去的数字index 从i 改成 i + 1,因为这里不需要重复的数字了。再有就是要设一个条件,如果一个重复的数字,不是出现在第一位的话,就跳过它。
Java Solution:
Runtime beats 83.86%
完成日期:07/17/2017
关键词:Array
关键点:Backtracking with sorted array
1 public class Solution 2 { 3 public List
> combinationSum2(int[] candidates, int target) 4 { 5 List
> list = new ArrayList<>(); 6 Arrays.sort(candidates); 7 backtrack(list, new ArrayList<>(), candidates, target, 0); 8 9 return list;10 }11 12 public boolean backtrack(List
> list, List tempList, 13 int[] nums, int remain, int start)14 {15 if(remain < 0) // if remain is 0 or less than 0, meaning the rest numbers are even greater16 return false; // therefore, no need to continue the loop, return false17 else if(remain == 0)18 {19 list.add(new ArrayList<>(tempList));20 return false;21 }22 else23 {24 for(int i=start; i start && nums[i] == nums[i-1])27 continue;28 boolean flag;29 tempList.add(nums[i]);30 flag = backtrack(list, tempList, nums, remain - nums[i], i+1); // i + 1 because we cannot use same number.31 tempList.remove(tempList.size() - 1);32 33 if(!flag) // if find a sum or fail to find a sum, there is no need to continue34 break;// because it is a sorted array with no duplicates, the rest numbers are even greater.35 }36 37 return true; // return true because previous tempList didn't find a sum or fail a sum38 }39 40 }41 }
参考资料:
http://www.cnblogs.com/grandyang/p/4419386.html
LeetCode 算法题目列表 -