给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

原题链接
可参考这题 组合从n个数中取k个数
组合题解
代码:

class Solution {
public:
    vector<vector<int>>ans;
    vector<vector<int>> subsets(vector<int>& nums) {
        int n = nums.size();
        vector<int>path;
        ans.push_back(path);            //先把[]放进去
        for(int i = 1; i <= n; i++)     //从数组nums的nums.size() 个数中取i个数
            dfs(nums,path,0,n,i);
        
        return ans;            
    }
    void dfs(vector<int>&nums,vector<int>&path,int start,int n,int k)
    {
        if(!k)
        {
            ans.push_back(path);
            return;
        }
        for(int i = start; i < n; i++)
        {
            path.push_back(nums[i]);
            dfs(nums,path,i+1,n,k-1);
            path.pop_back();
        }
    }
};

leetcode 78.子集 dfs解法

相关文章:

  • 2022-12-23
  • 2021-07-06
  • 2021-09-05
  • 2021-07-28
  • 2021-05-24
  • 2021-04-11
  • 2022-03-08
  • 2021-04-20
猜你喜欢
  • 2022-01-27
  • 2021-12-26
  • 2021-06-12
  • 2021-05-18
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案