[LeetCode]40 和的组合 II
来源:互联网 发布:软件测试的基础理论 编辑:程序博客网 时间:2024/06/07 23:32
Combination Sum II(和的组合 II)
【难度:Medium】
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]
LeetCode 39题的延伸,在39题的基础上增加了数组有重复数字这一情况,并且不允许出现重复的答案组合。
解题思路
有了39题的经验,此题同样可以沿用39题的解法——回溯来解决,要考虑的是如何避免重复。如果使用39题的代码会发现有两个相同的组合[1,7]和[7,1],所以只要解决了去重的问题即可。
c++代码如下:
class Solution {public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> ans; vector<int> tmp; if (candidates.empty()) return ans; quicksort(candidates,0,candidates.size()-1); if (target < candidates[0]) return ans; tranverse(ans,candidates,tmp,target,0); return ans; } void quicksort(vector<int>& n, int low, int high) { if (low >= high) return; int i = low; int j = high; int k = n[low]; while (i < j) { while (i < j && n[j] >= k) j--; n[i] = n[j]; while (i < j && n[i] <= k) i++; n[j] = n[i]; } n[i] = k; quicksort(n,low,i-1); quicksort(n,i+1,high); } void tranverse(vector<vector<int>>& ans, vector<int> n, vector<int>& tmp, int t, int index) { if (t == 0) { ans.push_back(tmp); return; } for (int i = index; i < n.size(); i++) { if (t < n[i]) break; /*去重的判断在于i == index || n[i] != n[i-1]*/ if ((t == n[i] || t >= 2*n[i]) && (i == index || n[i] != n[i-1])) { tmp.push_back(n[i]); tranverse(ans,n,tmp,t-n[i],i+1); tmp.pop_back(); } } return; }};
- [LeetCode]40 和的组合 II
- Leetcode Subsets II 有重复元素的组合
- LeetCode Subsets II (带有重复元素的组合)
- LeetCode 47. Permutations II(生成不同的组合-dfs)
- leetCode 40.Combination Sum II(组合总和II) 解题思路和方法
- [LeetCode]39 和的组合形式
- [LeetCode]Subsets II生成组合序列
- Combination Sum II 无序数组中找组合(每个元素只能用一次)使得和为target@LeetCode@LeetCode
- Unique Binary Search Trees II 输出二叉树的所有组合@LeetCode
- [LeetCode] Combination Sum 和确定的组合数的个数
- LeetCode Path Sum II路径和II
- Leetcode #40. Combination Sum II 组合求和2 解题报告
- LeetCode 40. Combination Sum II(组合求和)
- LeetCode | Combination Sum II(元素的和---2)
- 组合数的生成(II)
- joj 2062 Sum II (搜索是否存在指定和的组合)
- LeetCode Subsets 和 LeetCode Subsets II
- LeetCode--------39. Combination Sum(组合和)
- 第一行代码-13.2 使用Intent传递对象
- 将网页添加至阅读列表——SSReadingList
- 小刚的Android研究笔记~在未开启USB调试的Android手机绕过锁屏密码
- 自我介绍
- 软考大纲
- [LeetCode]40 和的组合 II
- jQuery面试题答案
- 数论+dfs+复数除法剪枝 Secret Code hdu1111
- Linux系统运维/vi的额外功能/4
- 20jquery题
- Linux入门学习教程:在Ubuntu 14.04中安装使用搜狗拼音输入法
- 计算机独立本科考试
- python---通过networkx使图着色结果可视化
- day07—SQL基本查询