生成一个集合的所有子集 Subset

142 篇文章 20 订阅
29 篇文章 0 订阅

典型的递归状态生成问题。类似于全排列的生成问题。


问题一:无重复元素集合的子集。Given a set of distinct integers, S, return all possible subsets.

思路:借助一个now数组存储临时的子集。不断切换状态进行深层递归,在递归最深处保存生成的子集。

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int> > result;
        if(S.empty()) return result;
        sort(S.begin(), S.end());
        vector<int> now;
        fun(S, result, now, 0);
        return result;
    }
    
    void fun(const vector<int> &s, vector<vector<int> > &result, vector<int> &now, int n)
    {
        if(n == s.size())
        {
            result.push_back(now); //递归最深处:所有元素都判定过取或不取
            return;
        }
        else
        {
            fun(s, result, now, n+1); //不取
            now.push_back(s[n]);
            fun(s, result, now, n+1); //取
            now.pop_back(); //回溯前一定要恢复回原样
        }
        
    }
};

问题二:有重复元素集合的子集。Given a collection of integers that might contain duplicates, S, return all possible subsets.

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> > result;
        vector<int> now;
        sort(S.begin(), S.end());//排序
        set<vector<int> > s;
        backtrack(s, now, S, 0);
        set<vector<int> >::iterator it = s.begin();
        for(;it != s.end();it++)
            result.push_back(*it);
        return result; 
    }
    
    void backtrack(set<vector<int> > &result, vector<int> &now, vector<int> &S, int idx)
    {
        if(idx == S.size())
        {
            result.insert(now);//set去重复
            return;
        }
        backtrack(result, now, S, idx+1);
        now.push_back(S[idx]);
        backtrack(result, now, S, idx+1);
        now.pop_back();
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值