LeeCode Subsets 子集问题解答分析

来源:互联网 发布:win7 python环境变量 编辑:程序博客网 时间:2024/06/06 03:20

 

Given a set of distinct integers, 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,3], a solution is:

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

 

这道题的思考方法很重要,要学会为电脑思考,怎么填写子集才是电脑最快捷方便的方法呢。

下面看看举例这个过程是如何的,现在假设有集合{1,2,3,4}如何求出他的所有子集呢:

初始化子集有的元素:

()

第一次循环:

Pushu_back现有的元素到vector<vector<int>>容器的尾部

得到:

()

然后再在新copy的元素后面添加当前循环i的值,比如v[i]=1,添加在后面(之前没有原有的vector<int>后面不需要添加,比如这里原有的是第一个(),现在新push_back了一个(),那么就得到:

(1)

现有元素:

()

(1)

第二次循环:

Pushu_back现有的元素到vector<vector<int>>容器的尾部

得到:

()

(1)

()

(1)

然后再在新copy的元素后面添加当前循环i的值

(2)

(1,2)

现有元素:

()

(1)

(2)

(1,2)

第三次循环:

Pushu_back现有的元素到vector<vector<int>>容器的尾部

得到:

()

(1)

(2)

(1,2)

()

(1)

(2)

(1,2)

 

然后再在新copy的元素后面添加当前循环i的值

(3)

(1,3)

(2,3)

(1,2,3)

现有元素

()

(1)

(2)

(1,2)

(3)

(1,3)

(2,3)

(1,2,3)

第四次循环:

Pushu_back现有的元素到vector<vector<int>>容器的尾部

得到:

()

(1)

(2)

(1,2)

(3)

(1,3)

(2,3)

(1,2,3)

()

(1)

(2)

(1,2)

(3)

(1,3)

(2,3)

(1,2,3)

然后再在新copy的元素后面添加当前循环i的值

(4)

(1,4)

(2,4)

(1,2,4)

(3,4)

(1,3,4)

(2,3,4)

(1,2,3,4)

现有元素

()

(1)

(2)

(1,2)

(3)

(1,3)

(2,3)

(1,2,3)

(4)

(1,4)

(2,4)

(1,2,4)

(3,4)

(1,3,4)

(2,3,4)

(1,2,3,4)

按照这个思路就很好写程序:

class Solution {public:vector<vector<int> > subsets(vector<int> &S) {sort(S.begin(), S.end());vector<vector<int> > v(1);for(int i = 0; i < S.size(); ++i) {int k = v.size();for (int j = 0; j < k; j++){v.push_back(v[j]);v.back().push_back(S[i]);}}return v;}};


参考程序:LeetCode

他的原程序是这样的:

class Solution {public:vector<vector<int> > subsets(vector<int> &S) {sort(S.begin(), S.end());vector<vector<int> > v(1);for(int i = 0; i < S.size(); ++i) {int j = v.size();while(j-- > 0) {v.push_back(v[j]);v.back().push_back(S[i]);}}return v;}};


两个有什么不一样呢?输出子集的顺序不一样,运行结果如下:

我是觉得这样好看一点,第一个程序:

第二个程序:

测试主程序:

int main(){int a[] = {1,2,3,4};vector<int> va(a, a+4);Solution solu;vector<vector<int> > vvi = solu.subsets(va);for (auto x:vvi){for (auto y:x)cout<<y<<" ";cout<<endl;}system("pause");return 0;}


 

 

//2014-2-12 updatevector<vector<int> > subsets(vector<int> &S) {sort(S.begin(), S.end());vector<vector<int> > rs(1, vector<int>());for (int i = 0; i < S.size(); i++){for (int j = rs.size() - 1; j >= 0 ; j--){rs.push_back(rs[j]);rs.back().push_back(S[i]);}}return rs;}

 

原创粉丝点击