[leetcode-78]Subsets

本文深入探讨了在给定一组不重复整数的情况下,如何利用递归算法生成所有可能的子集(幂集)。通过详细的代码示例,阐述了核心思想:在每一层递归中选择一个元素,并将未被选中的元素传递到下一层递归,从而避免重复子集的产生。

Description

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

Solution

core idea:

  1. pick one element and pass the elements not picked before to next iteration.
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> empty;
        result.push_back(empty);
        
        if(nums.size() == 0) {
            return result;
        }
        
        for(int i = 1; i <= nums.size(); i++) {
            vector<int> record;
            powerset(result, record, nums, i);
        }
        
        return result;
    }
    
    void powerset(vector<vector<int>> &result, vector<int> &select, vector<int> &left, int count) {
        if(select.size() == count){
            result.push_back(select);
            return;
        }
        
        // select[] left[1,2,3,4]
        // select[1] left[2,3,4]
        // select[2] left[3,4]
        // select[3] left[4]
        // select[4] left[]
        
        for(int i = 0; i < left.size(); i++) {
            select.push_back(left[i]);
            vector<int> temp = left;
            temp.erase(temp.begin(), temp.begin() + i + 1);
            
            if(temp.size() + select.size()>= count) {
                powerset(result, select, temp, count);
            }
            
            select.pop_back();     
        }
        
        
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值