求出字符串的全部组合并按字典顺序输出,如abc的全组合为:a、b、c、ab、ac、bc、abc。
**
思路一:利用递归
**
在求n个字符长度为m的组合时,我们把这n个字符分成两部分:第一个字符和其余所有的字符。如果组合里包含第一个字符,则下一步在剩余n-1个字符里选出m-1个字符;如果组合里不包含第一个字符,则下一步在剩余n-1个字符里选出m个。也就是把求n个字符组成m的组合的问题分解成两个子问题。
最后将结果排序再删除相同的字符串即可。
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <limits.h>
#include <algorithm>
using namespace std;
vector<string> fun( string str, int index,int number) { //递归函数实现n个数中number个数的组合。
vector<string> s1,s2;
if (number <= 0 || index >= str.size())
return s1;
string s;
s += str[index];
s1=fun( str, index + 1, number - 1);
s2 = fun(str, index + 1, number);
vector<string> result;
if (s1.empty() && number==1) //当组合数number为1时,且返回的s1为NULL时,应直接将str[index]存入结果中。
result.push_back(s);
for (int i = 0; i < s1.size(); i++) {
string ss;
ss = s+s1[i];
result.push_back(ss);
}
for (int i = 0; i < s2.size(); i++) {
result.push_back(s2[i]);
}
return result;
}
bool myobject(string a, string b){//比较函数
if (strcmp(a.c_str(), b.c_str()) >= 0)
return false;
else
return true;
}
vector<string> combination(string str) {
vector<string>res;
if (str.empty())
return res;
for (int i = 0; i <= str.size(); i++) { //获取组合数为i的组合结果。
vector<string> res1;
res1 = fun( str, 0, i);
for (int j = 0; j < res1.size(); j++) {
res.push_back(res1[j]);
}
}
sort(res.begin(), res.end(), myobject); //将结果按照自定义的myobject()函数排序
vector<string>::iterator it = unique(res.begin(), res.end());//功能:对有序的容器重新排列,将第一次出现的元素从前往后排,其他重复出现的元素依次排在后面。返回值:返回迭代器,迭代器指向的是重复元素的首地址
res.erase(it, res.end());//删除相同的元素
return res;
}
void main() {
string str = "aab";
vector<string> result;
result = combination(str);
}
**
思路二:利用位运算实现全组合
**
对于ABC三个元素的全组合有以下情况:
001取A; 010取B;011取AB;100取C;101取AC;110取BC;111取ABC。
问题转化为了:求1—(2^n-1)中每一个数的二进制数中1的位置有哪些,有1的位置即是字符串中需要取的字符的位置。x<< (31 - y) >> 31 == -1 ,若该语句返回true,则可判断出x中的第y位是1。
最后将字符串排序再删除相同的元素即可。
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <limits.h>
#include <algorithm>
#include <math.h>
using namespace std;
bool myobject(string a, string b){
if (strcmp(a.c_str(), b.c_str()) >= 0)
return false;
else
return true;
}
vector<string> combination(string str) {
vector<string> result;
if (str.empty())
return result;
int n = str.size();
int nBit = 1<< n;
for (int i = 1; i < nBit; i++) {
string temp;
for (int j = 0; j < n; j++) {
if (i << (31 - j) >> 31 == -1) { //if条件判断i中第j位是否为1。
temp += str[j];
}
}
result.push_back(temp);
temp.clear();
}
sort(result.begin(), result.end(), myobject);
vector<string>::iterator it = unique(result.begin(), result.end());
result.erase(it, result.end());
return result;
}
void main() {
string str = "aabc";
vector<string> result;
result = combination(str);
}