Skip to content

Latest commit

 

History

History
56 lines (46 loc) · 959 Bytes

0078._subsets.md

File metadata and controls

56 lines (46 loc) · 959 Bytes

78. Subsets

难度: Medium

刷题内容

原题连接

内容描述

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
 [3],
 [1],
 [2],
 [1,2,3],
 [1,3],
 [2,3],
 [1,2],
 []
]

解题方案

思路 1

每个元素有两种选择,选与不选,可以使用K位二进制数组表示K个元素的选与不选。
vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> ans;
    for(int i=0;i<pow(2, nums.size());i++){
        vector<int> tmp;
        int index = 0;
        int j=i;
        while(j){
            if(j%2==1)
                tmp.push_back(nums[index]);
            index++;
            j/=2;
        }
        ans.push_back(tmp);
    }
    return ans;
}