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.
  • 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]
]

题目标签:Array

  这道题目和前面那一题本质一摸一样,不同之处是,这题每一个数字只能用一次,之前那题可以无限用;这一题给的array里有重复的,之前那题没有。所以只要之前那题做了,稍微改动一下就可以了。把递归下去的数字index 从i 改成 i + 1,因为这里不需要重复的数字了。再有就是要设一个条件,如果一个重复的数字,不是出现在第一位的话,就跳过它。

Java Solution:

Runtime beats 83.86%

完成日期:07/17/2017

关键词:Array

关键点:Backtracking with sorted array

 public class Solution
{
public List<List<Integer>> combinationSum2(int[] candidates, int target)
{
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(candidates);
backtrack(list, new ArrayList<>(), candidates, target, 0); return list;
} public boolean backtrack(List<List<Integer>> list, List<Integer> tempList,
int[] nums, int remain, int start)
{
if(remain < 0) // if remain is 0 or less than 0, meaning the rest numbers are even greater
return false; // therefore, no need to continue the loop, return false
else if(remain == 0)
{
list.add(new ArrayList<>(tempList));
return false;
}
else
{
for(int i=start; i<nums.length; i++)
{
if(i > start && nums[i] == nums[i-1])
continue;
boolean flag;
tempList.add(nums[i]);
flag = backtrack(list, tempList, nums, remain - nums[i], i+1); // i + 1 because we cannot use same number.
tempList.remove(tempList.size() - 1); if(!flag) // if find a sum or fail to find a sum, there is no need to continue
break;// because it is a sorted array with no duplicates, the rest numbers are even greater.
} return true; // return true because previous tempList didn't find a sum or fail a sum
} }
}

参考资料:

http://www.cnblogs.com/grandyang/p/4419386.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

上一篇:Bootstrap 排版


下一篇:ThinkInJava4读书笔记之第七章隐藏实施过程