78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
解题思路:
这个题是让求一数组的全部子集。假设这个数组有n的数字,每一个数字对应一位,这样我们就得到了一个n位的数字,样例的话就是可以看成是一个三位数的数字。我们用二进制01代表每一位的选取情况,比如101,该数的意思就是取第0位的数字和第2位的数字,对应样例就是[1,3]。这样的话,该问题其实就转换成了拿到一个二进制的数,然后将二进制对应位置的数添加到一个子集里。这里还隐含这个一个数学知识,就是一个集合的所有子集的个数是2^n。这样,就是遍历这个2^n的数,然后将数字对应转化成子集。
代码:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> sets;
sets.push_back({});
int n = nums.size();
for(int i=1; i<pow(2,n); i++) {
int index = i;
vector<int> tmp;
int cnt = 0;
while(index) {
if(index&1) {
tmp.push_back(nums[cnt]);
}
cnt++;
index >>= 1;
}
sets.push_back(tmp);
}
return sets;
}
};
//不知道为什么下面这份代码的运行时间居然是上面的三倍,可是只有变量名称不一样啊?不懂,求解。上面运行时间4ms,下面12ms
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> sets;
sets.push_back({});
int n = nums.size();
for(int i=1; i<pow(2,n); i++) {
int cnt = i, index=0;
vector<int> tmp;
while(cnt) {
if(cnt&1) {
tmp.push_back(nums[index]);
}
index++;
cnt >>= 1;
}
sets.push_back(tmp);
}
return sets;
}
};