题目:

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]

链接: http://leetcode.com/problems/combination-sum-ii/

题解:

依然是一道DFS + Backtracking题目。 与之前不同的是每个数字只允许使用一次。所以在回溯的循环里当 i > pos时,假如之后又重复的,continue。我们依然使用candidates[i],而且candidates[i + 1]假如等于candidates[i], 会在DFS的下一个阶段被使用到。当然假如不用这个巧妙的条件也可以, 可以在 target == 0的时候判断res中是否contains  list,这样的话运行速度会慢不少,但也可以AC.

Time Complexity - O(), Space Complexity - O()。 如何计算复杂度,智商捉急啊...

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if(candidates == null || candidates.length == 0)
return res;
Arrays.sort(candidates);
ArrayList<Integer> list = new ArrayList<>();
dfs(res, list, candidates, target, 0);
return res;
} private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] candidates, int target, int pos) {
if(target == 0) {
res.add(new ArrayList<Integer>(list));
return;
}
if(pos >= candidates.length || target < 0)
return; for(int i = pos; i < candidates.length; i++) {
if(i > pos && candidates[i] == candidates[i - 1]) //for i > pos, if duplicate,continue. we still use candidates[i]
continue;
list.add(candidates[i]);
dfs(res, list, candidates, target - candidates[i], i + 1);
list.remove(list.size() - 1);
}
}
}

二刷:

这里依然是用了跟上一题目很接近的方法。不同的地方在于,每个数字不可以被无限次。所以一个数只能一次,而且遇到重复数字我们要跳过。这样我们在for循环里要加入一条 -  if (i > pos && candidates[i] == candidates[i - 1]) continue; 并且在DFS的时候每次

每次新的position = i + 1, 并不是上一题的position = i。

看到有discuss里有方法用array来做backtracking,速度beat 99%,以后也可以把list改成array,试一试这种方法。

Java:

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
List<Integer> comb = new ArrayList<>();
combinationSum2(res, comb, candidates, target, 0);
return res;
} private void combinationSum2(List<List<Integer>> res, List<Integer> comb, int[] candidates, int target, int pos) {
if (target < 0) {
return;
} else if (target == 0) {
res.add(new ArrayList<>(comb));
}
for (int i = pos; i < candidates.length; i++) {
if (i > pos && candidates[i] == candidates[i - 1]) {
continue;
}
int num = candidates[i];
if (num > target) {
return;
}
comb.add(num);
combinationSum2(res, comb, candidates, target - num, i + 1);
comb.remove(comb.size() - 1);
}
}
}

三刷:

跟上题唯一不同就是递归时把控制position的变量从 i 变成了 i + 1,这样我们就不会对一个元素进行多次计算。

Java:

public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if (candidates == null) return res;
Arrays.sort(candidates);
findCombinations(res, new ArrayList<>(), candidates, target, 0);
return res;
} private void findCombinations(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int pos) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(list));
return;
}
for (int i = pos; i < candidates.length; i++) {
if (candidates[i] > target) break;
if (i > pos && candidates[i] == candidates[i - 1]) continue;
list.add(candidates[i]);
findCombinations(res, list, candidates, target - candidates[i], i + 1);
list.remove(list.size() - 1);
}
}
}

Reference:

https://leetcode.com/submissions/detail/51501884/

40. Combination Sum II的更多相关文章

  1. [Leetcode][Python]40: Combination Sum II

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 40: Combination Sum IIhttps://oj.leetco ...

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

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

  3. leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III

    39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...

  4. 【LeetCode】40. Combination Sum II (2 solutions)

    Combination Sum II Given a collection of candidate numbers (C) and a target number (T), find all uni ...

  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 (C) and a target number (T), find all unique combinations in ...

  7. LeetCode OJ 40. Combination Sum II

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

  8. 【一天一道LeetCode】#40. Combination Sum II

    一天一道LeetCode系列 (一)题目 Given a collection of candidate numbers (C) and a target number (T), find all u ...

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

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

  10. 39. Combination Sum + 40. Combination Sum II + 216. Combination Sum III + 377. Combination Sum IV

    ▶ 给定一个数组 和一个目标值.从该数组中选出若干项(项数不定),使他们的和等于目标值. ▶ 36. 数组元素无重复 ● 代码,初版,19 ms .从底向上的动态规划,但是转移方程比较智障(将待求数分 ...

随机推荐

  1. Laravel 5 基础(二)- 路由、控制器和视图简介

    查看 app/Http/routes.php Route::get('/', 'WelcomeController@index'); @是一个界定符,前面是控制器,后面是动作,表示当用户请求url / ...

  2. Perl 关于 use strict 的用法

    什么场合要用 use strict 当你的程序有一定的行数时,尤其是在一页放不下时,或者是你找不到发生错误的原因时. 为什么要用 use strict? 众多的原因之一是帮你寻找因为错误拼写造成的错误 ...

  3. CentOS 6.4 安装搭建 Scrapy 0.22 环境

    一.安装Python2.7.6 更新CentOS lib库文件 yum -y update 安装开发工具包 yum groupinstall -y development 安装扩展包 yum inst ...

  4. C# sogou地图API应用总结

    地图的初始化1.添加引用地图的API文件: <script src="http://api.go2map.com/maps/js/api_v2.5.1.js" type=&q ...

  5. [原创]PostgreSQL Plus Advanced Server配合crontab实现定时维护工作

    本文要实现的目标1.PostgreSQL定时全备2.定时删除归档WAL文件3.定时删除全备文件4.删除n天之前的数据库日志文件 实验环境操作系统:RHEL 6.3数据库:PostgreSQL Plus ...

  6. View模版的设计

    一个Action多套View模版的设计   回到目录 模块化 这个问题是在做模块化设计时出现的,在Lind.DDD.Plugins模块里,需要对应的模块实体,模块管理者,模块标识接口等,开发时,如果你 ...

  7. Android bluetooth low energy (ble) writeCharacteristic delay callback

    I am implementing a application on Android using BLE Api (SDK 18), and I have a issue that the trans ...

  8. NodeJS学习笔记(转载)

    前言 让nodeJS跑起来 文件结构 node_modules/ejs app.js 路由 路由规则 添加路由规则 注册功能 MongoDB 安装MongoDB 链接MongoDB 结语 前言 最近同 ...

  9. Ubuntu 常用软件安装方法

    macubuntu 安裝方法: $wget https://github.com/downloads/ChinaLuo/Mac_Ubuntu/Mac_Ubuntu-12.04.tar.gz -O /t ...

  10. 玩转SmartQQ之登录

    SmartQQ是腾讯新出的一个WebQQ,登录地址是:http://w.qq.com/,目前之前的WebQQ可以继续使用,登录地址:http://web2.qq.com/webqq.html,Smar ...