78. Subsets

Problem:

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],
  []
]

思路
采用递归的思想。首先设一个包含空vector类型的变量res,然后每次添加nums中的一个元素num,在当前res中的所有元素后面加上num即可。

Solution:

vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> res = {{}};
        
    for (int num : nums) {
        int n = res.size();
        for (int i = 0; i < n; i++) {
            res.push_back(res[i]);
            res.back().push_back(num);
        }
    }
    return res;
}

性能
Runtime: 4 ms  Memory Usage: 9.1 MB

posted @ 2020-02-02 08:54  littledy  阅读(115)  评论(0)    收藏  举报