Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

39. Combination Sum的变形,39题数组中的数字可以重复使用,而这道题数组中的数字不能重复使用。这里要考虑跳过重复的数字,其它的与39题一样。

解法:和39一样,递归 + backtracking

Java:

public List<List<Integer>> combinationSum2(int[] cand, int target) {
Arrays.sort(cand);
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
dfs_com(cand, 0, target, path, res);
return res;
}
void dfs_com(int[] cand, int cur, int target, List<Integer> path, List<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList(path));
return ;
}
if (target < 0) return;
for (int i = cur; i < cand.length; i++){
if (i > cur && cand[i] == cand[i-1]) continue;
path.add(path.size(), cand[i]);
dfs_com(cand, i+1, target - cand[i], path, res);
path.remove(path.size()-1);
}
}  

Java:

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> curr = new ArrayList<Integer>();
Arrays.sort(candidates);
helper(result, curr, 0, target, candidates);
return result;
} public void helper(List<List<Integer>> result, List<Integer> curr, int start, int target, int[] candidates){
if(target==0){
result.add(new ArrayList<Integer>(curr));
return;
}
if(target<0){
return;
} int prev=-1;
for(int i=start; i<candidates.length; i++){
if(prev!=candidates[i]){ // each time start from different element
curr.add(candidates[i]);
helper(result, curr, i+1, target-candidates[i], candidates); // and use next element only
curr.remove(curr.size()-1);
prev=candidates[i];
}
}
}  

Python:

class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
prev = 0
while start < len(candidates) and candidates[start] <= target:
if prev != candidates[start]:
intermediate.append(candidates[start])
self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start])
intermediate.pop()
prev = candidates[start]
start += 1

C++:

class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > res;
vector<int> out;
sort(num.begin(), num.end());
combinationSum2DFS(num, target, 0, out, res);
return res;
}
void combinationSum2DFS(vector<int> &num, int target, int start, vector<int> &out, vector<vector<int> > &res) {
if (target < 0) return;
else if (target == 0) res.push_back(out);
else {
for (int i = start; i < num.size(); ++i) {
if (i > start && num[i] == num[i - 1]) continue;
out.push_back(num[i]);
combinationSum2DFS(num, target - num[i], i + 1, out, res);
out.pop_back();
}
}
}
};  

类似题目:

[LeetCode] 39. Combination Sum 组合之和

[LeetCode] 40. Combination Sum II 组合之和 II的更多相关文章

  1. [LeetCode] 377. Combination Sum IV 组合之和 IV

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  2. [LeetCode] 216. Combination Sum III 组合之和 III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  3. [LeetCode] 377. Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  4. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  5. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  6. [LeetCode] 40. Combination Sum II 组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

  7. LeetCode OJ:Combination Sum II (组合之和 II)

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  8. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  9. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. python学习之多窗口切换

    多窗口切换: from selenium import webdriver d = webdriver.Firefox() d.window_handles #显示所有的窗口 d.current_wi ...

  2. centos服务器上git clone下载加速

    最近在服务器上直接git clone github上的仓库,下载速度只有十几KB,简直不要太慢! 网上搜了一些加速的,自己于是写了下面的总结. 1. nslookup命令 如果执行这个命令找不到,请先 ...

  3. EF 多数据库切换配置(MSSQL/MySql)

    <?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访 ...

  4. npm包之npm-check-updates

    检查npm的依赖包是否有比较新的版本 安装 npm i -g npm-check-updates 使用 ncu --help // 查看相关命令 ncu // 检查当前项目中有没有哪些依赖包可更新 n ...

  5. 学习:类和对象——对象模型和this指针

    成员变量和成员函数分开存储: 在C++中,类内的成员变量和成员函数分开存储 第一点:空对象占用内存空间1个字节 第二点:只有非静态成员变量才属于类的对象上,非静态成员函数和静态成员函数和静态成员变量不 ...

  6. 基于思岚A1激光雷达+OpenGL+VS2017的Ramer-Douglas-Peucker算法的实现

    时隔两年 又借到了之前的那个激光雷达,最老版本的思岚A1,甚至不支持新的固件,并且转接板也不见了,看了下淘宝店卖¥80,但是官方提供了一个基于STM32的实现方式,于是我估摸着这个转接板只是一个普通的 ...

  7. LOJ P10130 点的距离 题解

    这道题相当于倍增求LCA的板子,我们只要构建一棵树,然后距离就是x的深度+y的深度 - LCA(x,y)的深度: #include<iostream> #include<cstdio ...

  8. js解决大文件断点续传

    最近遇见一个需要上传百兆大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现. 在某些业务中,大文件上传是一个比较重要的交互场景,如上传入库比较大的Excel表 ...

  9. learning scala list.collect

    collect will apply a partial function to all elements of a Traversable and return a different collec ...

  10. fake_useragent 本地运行各种报错解决办法