Leetcode Subsets II
来源:互联网 发布:淘宝店什产品最好卖 编辑:程序博客网 时间:2024/06/03 21:37
Leetcode Subsets II,本问题与Subsets 类似,只是需要处理重复子集问题,这个问题,我们可以使用每次从长度为m的子集构成长度为m+1的子集时,只对等值的元素添加一次,这样就可以保证没有重复现象,处理代码与Subsets类似,如下:
#include<iostream>#include<vector>#include<algorithm>using namespace std;class Solution {public: vector<vector<int> > subsetsWithDup(vector<int>& nums) { // Sort the nums for the left solution sort(nums.begin(), nums.end()); int len = nums.size(); // Init the result vector re vector<vector<int> > re; re.push_back(vector<int>()); // The pos vector saves the last element postion of the re[i] // in the nums. vector<int> pos; // The first element in re is empty, so the first value is -1 pos.push_back(-1); // The start and end position of the length k element in re int start = 0; int end = 0; while (re.back().size() != len) { // The elements of re with length k can be formed by the elements // of re with length k-1 append an element after its last element for (int i = start; i <= end; i ++) { for (int j = pos[i] + 1; j < len; j ++) { // Every time construct the element with length k // for element with length k-1 only include the elements // in nums with equaling values once if ((j == pos[i] + 1) || (j != 0 && nums[j] != nums[j - 1])) { vector<int> temp(re[i]); temp.push_back(nums[j]); re.push_back(temp); pos.push_back(j); } } } //Update the start and end position of elements with length k start = end + 1; end = re.size() - 1; } return re; }};int main(int argc, char* argv[]) { Solution so; vector<int> test; test.push_back(2); test.push_back(1); test.push_back(2); test.push_back(3); vector<vector<int> > re = so.subsetsWithDup(test); for (int i = 0; i < re.size(); i ++) { for (int j = 0; j < re[i].size();j ++) { cout<<re[i][j]<<" "; } cout<<endl; } return 0;}
0 0
- 【LeetCode】 Subsets Subsets II
- 【LeetCode】Subsets & Subsets II
- LeetCode Subsets && Subsets II
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- [LeetCode] Combinations、Subsets、Subsets II
- 【Leetcode】【python】Subsets/Subsets II
- LeetCode: Subsets II
- LeetCode SubSets II
- LeetCode: Subsets II
- leetcode 48: Subsets II
- [LeetCode] Subsets II
- [Leetcode] Subsets II
- [leetcode] Subsets II
- leetcode Subsets II
- leetcode Subsets II problem
- [LeetCode]Subsets II
- [leetcode]Subsets II
- An iOS Developer on React Native一个资深iOS开发者对于React Native具体使用体验
- C#和SqlServer计算地理位置之间的距离
- Oracle死锁查询及处理方法
- iOS项目管理
- MSMQ消息广播
- Leetcode Subsets II
- cocos2dx 2.0版本在android下的安装配置问题
- Esri与开源
- 监听键盘高度变化,以及键盘自定义
- iOS代码实践总结
- ArcGIS Server创建缓存地图服务教程
- 数据结构 (五)c++函数和参数传递 按值传递 按引用传递
- RSA加密实践
- 利用cxf实现webservice完整demo