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.
- 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的更多相关文章
- [Leetcode][Python]40: Combination Sum II
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 40: Combination Sum IIhttps://oj.leetco ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III
39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...
- 【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 ...
- [LeetCode] 40. Combination Sum II 组合之和之二
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- LeetCode OJ 40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【一天一道LeetCode】#40. Combination Sum II
一天一道LeetCode系列 (一)题目 Given a collection of candidate numbers (C) and a target number (T), find all u ...
- [leetcode]40. Combination Sum II组合之和之二
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
- 39. Combination Sum + 40. Combination Sum II + 216. Combination Sum III + 377. Combination Sum IV
▶ 给定一个数组 和一个目标值.从该数组中选出若干项(项数不定),使他们的和等于目标值. ▶ 36. 数组元素无重复 ● 代码,初版,19 ms .从底向上的动态规划,但是转移方程比较智障(将待求数分 ...
随机推荐
- Hiberante+jpa,注解生成32字符的Id
@Id @GenericGenerator(name = "id-generator", strategy = "uuid") @GeneratedValue( ...
- SQLIO Disk Subsystem Benchmark Tool
C:\Program Files (x86)\SQLIO>sqlio -? sqlio v1.5.SG -?: invalid option Usage: sqlio [options] [&l ...
- [CSS]学习总结
1. 遮挡层 .occlusion { opacity: -.35;/*透明程度*/ -moz-opacity: -.35; filter: alpha(opacity=-35); height: 1 ...
- linux编码
转: Linux查看文件编码格式及文件编码转换 如果你需要在Linux中操作windows下的文件,那么你可能会经常遇到文件编码转换的问题.Windows中默认的文件格式是GBK(gb2312),而L ...
- 从零开始学ios开发(十):Multiview Applications(多个xib之前的切换)
这篇学习的主要内容是Multiview,在我们学习iphone旋转的时候,介绍过多个view的使用方法,不过这里的view和旋转屏幕中所指的多个view是不同的,旋转屏幕中涉及到的多个view是在一个 ...
- API网关
API网关 最开始只是想找个API网关防止API被恶意请求,找了一圈发现基于Nginx的OpenResty(Lua语言)扩展模块Orange挺好(也找了Kong,但是感觉复杂了点没用),还偷懒用Vag ...
- crawler spec
使用说明 0.写在前面 1.本程序完成的抓取网页并保存其文件的工作. 2.目前的版本还需将工程文件导入eclipse中运行. 3.加载主类MyCrawler生成可执行文件. 4.程序主界面: 1 准备 ...
- Cookie 获取
二级域名可以获取一级域名的Cookie值 二级域名下删除顶级域名下的Cookie,需要添加顶级域名的Cookie作用域 /// <summary> /// 根据cookie名称删除 /// ...
- 那些我用过的Android开源项目
1.RefreshActionItem 基于ActionBarSherlock库的一个扩展,在标题栏右边显示多种刷新效果的UI按钮. 项目主页: https://github.com/ManuelPe ...
- jquery 取值赋值
<input type="text" id="range_complete" /> $('#range_complete').val();//取值 ...