首页 技术 正文
技术 2022年11月8日
0 收藏 730 点赞 1,858 浏览 1486 个字

Given a collection of integers that might contain duplicates, S, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If S = [1,2,2], a solution is:

[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

思路:回溯法是肯定的了,我用的深度优先,先把输入的S排序,这样当考虑了前面的数字后,后面的讨论中就不需要再考虑该数字了。需要对每次的子序列判断是否已经重复出现。

代码AC了,但是800ms太慢,贴边过的。

class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>> ans;
vector<int> null;
ans.push_back(null); if(S.size() == )
return ans; sort(S.begin(), S.end());
DFS(ans, S);
return ans;
} void DFS(vector<vector<int>> &ans, vector<int> S)
{
if(S.empty())
return; vector<int> vPreLen = ans.back();
while(!S.empty())
{
vector<int> v = vPreLen;
int cur = S[];
v.push_back(cur);
S.erase(S.begin());
if(!isalreadyhave(ans, v))
{
ans.push_back(v);
DFS(ans, S);
}
}
return;
} bool isalreadyhave(vector<vector<int>> ans, vector<int> v)
{
for(int i = ; i < ans.size(); i++)
{
if(v == ans[i])
return true;
}
return false;
}
};

大神的思路:48ms

在压入答案的时候就保证不会重复,把重复的部分如(5,5,5)看做一个特殊的数,压入时可以压入1个、2个、3个。

把S排序后,按顺序从第一个到最后一个得到该数字加入后,可以得到的新的子序列。每次加入一个新的数字后,新的数字会使得所有之前已经压入的子序列产生新的子序列。

class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > totalset = {{}};
sort(S.begin(),S.end());
for(int i=; i<S.size();){
int count = ; // num of elements are the same
while(count + i<S.size() && S[count+i]==S[i]) count++;
int previousN = totalset.size();
for(int k=; k<previousN; k++){
vector<int> instance = totalset[k];
for(int j=; j<count; j++){
instance.push_back(S[i]);
totalset.push_back(instance);
}
}
i += count;
}
return totalset;
}
};
下一篇: CCF 节日
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,489
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,290