腾讯//子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
class Solution {
public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
int all = 1<<n;
List<List<Integer>> res = new ArrayList<>();//存放最后的结果
for(int i = 0; i < all; i++){
List<Integer> list = new ArrayList<>();
for(int j = 0; j < nums.length; j++){
if((i & (1<<j)) != 0){
list.add(nums[j]);
}
}
res.add(list);
}
return res;
}
}
可以将数组中的每个数与0或者1相对应,从[0,0,0]开始到[1,1,1]
使用与运算
用i分别与上001,010,100,来表示i中哪一位为1,i从0开始循环一直到2^n
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res(1);
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); i++){
int size = res.size();
for(int j = 0; j < size; j++){
res.push_back(res[j]);
res.back().push_back(nums[i]);
}
}
return res;
}
};
class Solution {
public:
vector<vector<int> > subsets(vector<int> &nums) {
vector<vector<int>> res;
vector<int> out;
sort(nums.begin(), nums.end());
getSubsets(nums, 0, out, res);
return res;
}
void getSubsets(vector<int> &nums, int pos, vector<int> &out, vector<vector<int>> &res){
res.push_back(out);
for(int i = pos; i < nums.size(); i++){
out.push_back(nums[i]);
getSubsets(nums, i+1, out, res);
out.pop_back();
}
}
};
class Solution {
public:
vector<vector<int> > subsets(vector<int> &nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int max = 1<<nums.size();
for(int i = 0; i < max; i++){
vector<int> out = convertIntToSet(nums,i);
res.push_back(out);
}
return res;
}
vector<int> convertIntToSet(vector<int> &nums, int i){
vector<int> sub;
int idx = 0;
for(int j = i; j > 0; j>>=1){
if((j&1)==1)
sub.push_back(nums[idx]);
idx++;
}
return sub;
}
};