Leetcode--Subsets

来源:互联网 发布:美国队长3知乎 编辑:程序博客网 时间:2024/05/21 14:41

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],  []]

Hide Tags
 Array Backtracking Bit Manipulation
Have you been asked this question in an interview?


思路: backtracing
class Solution {public:    vector<vector<int>> res;    //set<vector<int>> res;    void function(int start,int len,vector<int> s,vector<int> tmp)    {if(tmp.size()==len)            res.push_back(tmp);        else{for(int i=start;i<=s.size()-(len-tmp.size());i++){vector<int> v(tmp);v.push_back(s[i]);function(i+1,len,s,v);}        }    }    vector<vector<int> > subsets(vector<int> &S) {        if(S.size()<0)            return res;        else if(S.size()==0)        {            vector<int> tmp;            res.push_back(tmp);            return res;        }        else{            vector<int> tmp;            res.push_back(tmp);            sort(S.begin(),S.end());            for(int len=1;len<=S.size();len++)//控制长度            {function(0,len,S,tmp);            }            return res;        }    }};




0 0
原创粉丝点击