问题描述
思路
这种求子集的题目都是一个套路,递归+深度优先遍历;差别是遍历的过程中入答案队列的条件不一样
和Leetcode 46:全排列那题可以结合一起看
CPP
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> tmp;
int n = nums.size();
dfs(ans,nums,tmp,0,n);
return ans;
}
void dfs(vector<vector<int>> &ans,vector<int>& nums,vector<int> &tmp,int k,int n){
ans.push_back(tmp);
for(int i = k;i < n;i++)
{
tmp.push_back(nums[i]);
dfs(ans,nums,tmp,i+1,n);
tmp.pop_back();
}
}
};
GO
func subsets(nums []int) [][]int {
n := len(nums)
ans := make([][]int,0)
tmp := make([]int,0)
dfs(&ans,tmp,nums,0,n)
return ans
}
func dfs(ans *[][]int,tmp []int,nums []int,k,n int) {
tmpVec := make([]int,len(tmp))
copy(tmpVec,tmp)
*ans = append(*ans,tmpVec)
for i:=k;i < n;i++{
tmp = append(tmp,nums[i])
dfs(ans,tmp,nums,i+1,n)
tmp = tmp[:len(tmp) - 1]
}
}