题目描述:
Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Hide Tags Array Backtracking Bit Manipulation
分析:
要求数组的子集,那么根据子集的定义,只需取出这n个数的不同的组合,排下序即可。
此题有多种方法,但是我只会位运算一种。
首先对原数组利用sort函数排序。
然后定义一个最大是n个位1组成的数,然后变换每个位上面的0和1,一共对应有2^n-1个数,每一个数对应一个子集,对于一个数将位1对应下标的数组元素加进子集中。最后将所有子集加入结果集中即可。
Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Hide Tags Array Backtracking Bit Manipulation
分析:
要求数组的子集,那么根据子集的定义,只需取出这n个数的不同的组合,排下序即可。
此题有多种方法,但是我只会位运算一种。
首先对原数组利用sort函数排序。
然后定义一个最大是n个位1组成的数,然后变换每个位上面的0和1,一共对应有2^n-1个数,每一个数对应一个子集,对于一个数将位1对应下标的数组元素加进子集中。最后将所有子集加入结果集中即可。
以下是C++实现代码:
/**///9ms*/
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
if(n == 0)
return res;
sort(nums.begin(),nums.end()); //sort nums
int k = 1<<n;
for(int i = 0; i < k; i++){ //the subset who contains count i numbers
int id = 0,j = i;
vector<int> vec;
while(j > 0){
if(j & 1) //whether the last bit is 1
vec.push_back(nums[id]);
id++;
j = j>> 1;
}
res.push_back(vec);
}
return res;
}
};