10.8 Combination Sum II
来源:互联网 发布:mac 照片 iphoto 区别 编辑:程序博客网 时间:2024/04/30 04:12
Link: https://oj.leetcode.com/problems/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]
The only difference between 10.8 and 10.7 Combination Sum, is "Each number in C may only be used once in the combination."
Time: O(n!), Space: O(n)
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();Arrays.sort(num);dfs(num, 0, target, new ArrayList<Integer>(), result);return result; } public void dfs(int[] num, int start, int target, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> result){if(target == 0){ result.add(new ArrayList<Integer>(tmp));}for(int i = start; i < num.length; i++){ if(target < num[i]) return; if(i>start && num[i] == num[i-1]) continue; tmp.add(num[i]); dfs(num, i+1, target-num[i], tmp, result); tmp.remove(tmp.size()-1);}}}
if(i>start && num[i] == num[i-1]) continue;cannot be coded as
if(i>0 && num[i] == num[i-1]) continue;Otherwise, we will have wrong answer:
Input:[1,1], 2
Output:[]
Expected:[[1,1]]
0 0
- 10.8 Combination Sum II
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- Combination Sum II
- leetcode Combination Sum II
- Combination Sum II
- ucos代码裁剪
- 电话豆腐花发过火和规范化
- 看到这篇文章,我笑了,我结婚,丈母娘就给两百块钱的压箱底钱,最后什么都没了》
- 程序员的两难抉择
- hdu 1000
- 10.8 Combination Sum II
- hdu 1001
- windows下Eclipse安装hadoop1.1.2插件连接hadoop集群
- GUI_Delay函数
- Ruby中hash作为函数参数特殊性比较
- hdu 1002
- JFinal 源码超详细解析之DB+ActiveRecord
- 过气明星的辛酸生活:唐僧走穴捞金小龙女变大妈
- VC++实现监视系统的键盘操作 创建记录键盘动作的全局钩子DLL