[LeetCode]—Subsets 求数组子集

来源:互联网 发布:评价耶稣知乎 编辑:程序博客网 时间:2024/04/28 16:36

Subsets

 

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],  []]
分析:

        每个元素,都有放或者不放两种选择。深搜问题。

       

class Solution {public:    vector<vector<int> > subsets(vector<int> &S) {       vector<vector<int> > res;       vector<int> sub;       sort(S.begin(),S.end());  //测试集给的是无序       DFS(res,sub,S,0);       return res;    }    void DFS(vector<vector<int> > &res,vector<int> &sub,vector<int> &S,int ind){       if(S.size()==ind){         res.push_back(sub);       }       else{           DFS(res,sub,S,ind+1);           sub.push_back(S[ind]);           DFS(res,sub,S,ind+1);           sub.pop_back();       }       return;    }};


方法二:

             观察上述搜索树,发现当前层的集合=上一层的集合+上一层集合加上当前元素的集合。那么有此规律,我们完全就可以省去递归开销。

  

class Solution {public:    vector<vector<int> > subsets(vector<int> &S) {        vector<vector<int> > res(1);  //初始有一个空集        vector<int> tmp;        sort(S.begin(),S.end());        for(int i=0;i<S.size();i++){            int n=res.size();            for(int j=0;j<n;j++){                tmp=res[j];                tmp.push_back(S[i]);                res.push_back(tmp);            }        }        return res;    }};


0 0
原创粉丝点击