输出一个集合的所有子集

来源:互联网 发布:恒指期货实时行情数据 编辑:程序博客网 时间:2024/06/05 18:44

输出字符串的所有子集

如:对“abc”

输出:

 c b bc a ac ab abc



第一种做法: 2^n 遍历每个字符,每个字符只能取或者不取。取就把该字符加入结果中,遍历完毕后,输出结果字符串。

代码如下:

////  main.cpp//  输出一个集合的所有子集////  Created by zjl on 16/8/10.//  Copyright © 2016年 zjl. All rights reserved.//#include <iostream>#include <vector>using namespace std;void solve(string s, string& str, vector<string>& res, int num){    if(num == s.size()){        res.push_back(str);        return;    }        solve(s, str, res, num+1);    str += s[num];    solve(s, str, res, num+1);    str.erase(str.size()-1);}int main(int argc, const char * argv[]) {    string s = "abc";    vector<string> res;    string str;    solve(s, str, res, 0);    for(auto a: res)        cout<<a<<" ";    cout<<endl;    return 0;}


第二种:

求字符串大小len,然后从1开始到len-1。

比如len=4, 则从1开始到3,每个为 001,010,011,100,101,111.

并对每个数字先跟1相与,并输出相应字符;然后往右>>移动,判断每个位置,若为1,则输出相应位置字符。


////  main.cpp//  输出一个集合的所有子集////  Created by zjl on 16/8/10.//  Copyright © 2016年 zjl. All rights reserved.//#include <iostream>#include <vector>using namespace std;void solve(string s, vector<string>& res){    int len = s.size();    int num = 1 << len;    for(int i = 1; i < num; i++){        int j = i;        int k = 0;        string str;        while(j){            if((j & 1) == 1){                str += s[k];            }            k++;            j = j >> 1;        }        res.push_back(str);    }    }int main(int argc, const char * argv[]) {    string s = "abc";    vector<string>res;    solve(s, res);    for(auto a: res)        cout<<a<<" ";    cout<<endl;    return 0;}






0 0
原创粉丝点击