Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

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

分析:  用位操作非常简单,对于n个数来说共有2^n个组合,每一个组合中n个数的每一个 在或者不在 两种情况

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
       
        int n=nums.size();
        int total = pow(2,n);
         vector<vector<int>> res(total);
        for(int i=0; i<n; i++){
            for(int j=0; j<total; j++){
                if(j>>i & 1)
                    res[j].push_back(nums[i]);
            }
        }
        return res;
    }
};

 

posted @ 2017-01-05 10:52  WillWu  阅读(130)  评论(0编辑  收藏  举报