已知字符串中的字符是互不相同的,现在把它们任意排列(例如,若已知字符是“ab”,则任意排列是“aa”,”ab”,”ba”,”bb”),编程按照字典序输出所有的组合。
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
void process(char*s, int len ,int k, char *com){
if(k == len){
for(int i = 0 ;i < len;i++)
cout<<com[i]<<" ";
cout<<endl;
return;
}
for(int i = 0 ;i<len;i++){
com[k] = s[i];
process(s,len,k+1,com);
}
}
int main(){
char s[] = "acb";
int len = strlen(s);
sort(s,s+len);
char *com = new char[len];
process(s,len,0,com);
delete []com;
}
字符的所有组合
如果不是求字符串中的所有字符的所有排列,而是求字符的所有组合,应该怎么办呢?当输入的字符串中包含相同的字符时,相同的字符交换位置是不同的排列,但是确是同一个组合。举一个例子,输入abc,它的组合有:a, b,c,ab,bc,ac,abc这些
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
void process(char*s, int len ,int k,vector<char>com){
if(k == len){
int len = com.size();
for(int i = 0; i < len;i++)
cout<<com[i]<<" ";
cout<<endl;
return;
}
com.push_back(s[k]);
process(s,len,k+1,com);
com.pop_back();
process(s,len,k+1,com);
}
int main(){
char s[] = "acb";
int len = strlen(s);
sort(s,s+len);
vector<char>com;
process(s,len,0,com);
}
输出组合数,比如从n个里面选择m个,求一共有哪几种组合方法
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
void process(char *s,int len, int index, char*com, int count){
if(index == 0){
for(int i = 1;i<= count;i++)
cout<<com[i]<<" ";
cout<<endl;
return ;
}
for(int i = len;i>=index;--i){
com[index] = s[i];
process(s,i-1,index-1,com,count);
}
}
int main(){
int len = 5;
char *s = new char[len+1];
for(int i = 1;i<=len;i++)
s[i] = i+'0';
int k = 2;
char *com = new char[k+1];
process(s,len,k,com,k);
delete com;
delete s;
}
编程之法序列打印P12
自己写的时间复杂度太高了…(根据上面的输出组合数,n个里面选择m个这个程序来改进的)
#include <iostream>
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
void process(char *s,int len, int index, char*com, int count){
if(index == 0){
cout<<"( ";
for(int i = 1;i<= count;i++)
cout<<com[i]<<", ";
cout<<"), ";
return ;
}
for(int i = len;i>=index;--i){
com[index] = s[i];
process(s,i-1,index-1,com,count);
}
}
int main(){
int len = 26;
char *s = new char[len+1];
for(int i = 1;i<=len;i++)
s[i] = i+'a'-1;
int k = 1;
while(k <=26){
char *com = new char[k+1];
process(s,len,k,com,k);
cout<<endl;
delete com;
k++;
}
}