[LeetCode]78.Subsets

160 篇文章 28 订阅

题目

Given a set of distinct integers, S, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

分析

充分利用[LeetCode]77.Combinations
本题其实对上题的拓展,上题是一种长度的组合,本题则是穷尽不同长度的组合。
假设S长度为Len,则令 0 <= K <= Len

代码

    /**------------------------------------
    *   日期:2015-02-06
    *   作者:SJF0115
    *   题目: 78.Subsets
    *   网址:https://oj.leetcode.com/problems/subsets/
    *   结果:AC
    *   来源:LeetCode
    *   博客:
    ---------------------------------------**/
    #include <iostream>
    #include <cstring>
    #include <vector>
    #include <algorithm>
    using namespace std;

    class Solution {
    public:
        vector<vector<int> > subsets(vector<int> &S) {
            int size = S.size();
            vector<vector<int> > result;
            vector<int> path;
            // 排序
            sort(S.begin(),S.end());
            // 空集
            result.push_back(path);
            // 其他子集
            for(int i = 1;i <= size;++i){
                DFS(S,size,i,0,path,result);
            }//for
            return result;
        }
    private:
        void DFS(vector<int> &s,int n,int k,int index,vector<int> &path,vector<vector<int> > &result){
            // 一个子集
            if(path.size() == k){
                result.push_back(path);
                return;
            }//if
            for(int i = index;i < n;++i){
                path.push_back(s[i]);
                DFS(s,n,k,i+1,path,result);
                path.pop_back();
            }//for
        }
    };

    int main(){
        Solution s;
        vector<int> num = {4,3,2};
        vector<vector<int> > result = s.subsets(num);
        // 输出
        for(int i = 0;i < result.size();++i){
            for(int j = 0;j < result[i].size();++j){
                cout<<result[i][j]<<" ";
            }//for
            cout<<endl;
        }//for
        return 0;
    }

运行时间

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值