概述
描述
给定一个含不同整数的集合,返回其所有的子集
子集中的元素排列必须是非降序的,解集必须不包含重复的子集
样例
如果 S = [1,2,3],有如下的解:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
挑战
你可以同时用递归与非递归的方式解决么?
思路
从右到左处理nums的元素,当res为空,将{},{nums.back()}存入res,并删除nums的末尾元素。若res不为空,对于每个元素res[i],加上nums.back(),再添加到res中,删除nums的末尾元素。直至nums为空。
#ifndef C17_H
#define C17_H
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(const int a, const int b)
{
return a > b;
}
class Solution {
public:
/**
* @param nums: A set of numbers
* @return: A list of lists
*/
vector<vector<int>> subsets(vector<int> &nums) {
// write your code here
if (nums.empty())
return{ {} };
//构建降序数组
sort(nums.begin(), nums.end(), cmp);
//从数组尾部开始添加数据
//新的res是原res再加上每个res元素加上nums的尾部
while (!nums.empty())
{
if (res.empty())
{
res.push_back({ nums.back() });
res.push_back({});
}
else
{
int len = res.size();
for (int i = 0; i < len; ++i)
{
vector<int> temp = res[i];
temp.push_back(nums.back());
res.push_back(temp);
}
}
nums.pop_back();
}
return res;
}
vector<vector<int>> res;
};
#endif
最后
以上就是跳跃鱼为你收集整理的子集 - LintCode的全部内容,希望文章能够帮你解决子集 - LintCode所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复