首页 > 代码库 > LeetCode 40. Combination Sum II (组合的和之二)

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

 

 1 public class Solution 
 2 {
 3     public List<List<Integer>> combinationSum2(int[] candidates, int target) 
 4     {
 5         List<List<Integer>> 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<Integer>> list, List<Integer> 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 greater
16             return false; // therefore, no need to continue the loop, return false
17         else if(remain == 0)
18         {
19             list.add(new ArrayList<>(tempList));
20             return false;
21         }
22         else
23         {
24             for(int i=start; i<nums.length; i++)
25             {
26                 if(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 continue
34                     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 sum
38         }
39 
40     }
41 }

参考资料:

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

 

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

 

LeetCode 40. Combination Sum II (组合的和之二)