Home LeetCode - 78. Subsets
Post
Cancel

LeetCode - 78. Subsets

78. Subsets - medium

문제

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
12
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

풀이

  • Recursive, Bit Manipulate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> answer;
        int max = 1 << (nums.size());
        
        for(auto i = 0 ; i < max ; ++i){
            vector<int> sub;
            for(auto j = 0 ; j < nums.size() ; ++j){
                if(i & (1 << j)) 
                    sub.push_back(nums[j]);
            }
            answer.push_back(sub);
        }
        
        return answer;
    }
};
This post is licensed under CC BY 4.0 by the author.