LeetCode算法系列: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的数组的子数组可以非为两种情况:一种是有该数组的最后一个元素,一个是没有该数组的最后一个元素
class Solution {
public:
    vector> res;
    vector oneres;
    vector> subsets(vector& nums) {
        int n = nums.size();
        recursive(nums, n);
        return res;
    }
    void recursive(vector& nums, int n){
        if(n == 0){
            res.push_back(oneres);
        }
        else{
            recursive(nums, n - 1);
            oneres.push_back(nums[n - 1]);
            recursive(nums, n - 1);
            oneres.pop_back();
        }
    }
};

 

你可能感兴趣的:(刷题系列(LeetCode,牛客等))