[LeetCode] Subsets

来源:互联网 发布:淘宝买家退款率8% 编辑:程序博客网 时间:2024/06/06 17:58

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

思想比较简单,0-2^n-1的二进制表示分别代表了以上的各个位置出现与否的各种组合。

class Solution {public:    vector<vector<int> > subsets(vector<int> &S) {        // Note: The Solution object is instantiated only once and is reused by each test case.        int size=S.size();        vector<vector<int>> res;        if(size==0){            return res;        }        sort(S.begin(),S.end());        int x=1<<size;        vector<int> temp;        for(int i=0;i<x;i++){            temp.clear();            int j=i;            int t=0;            while(j){               if(j&0x1==1){                   temp.push_back(S[t]);               }               j=j>>1;               t++;            }            res.push_back(temp);        }        return res;    }};


原创粉丝点击