方法:
对于一串字符,如果只有长度为1,那么组合方式自然自有一种;
如果长度为二(如1和2),那么对于1来说,2的放置方式有两种(1前和1后);
如果是1,2,3,这长度为三的字符串,我们就可以把1和2,将3插入12的的组合中(已知1,2有两种组合),3在每一种组合中可以有三种插入方式,共计6种;
以此类推的话,不难发现解决方法最好是使用递归(因为如果我是1-100的组合方式,我不可能去建立100个for循环,这样是十分不可取的!)
实现方法:
#include<vector>
#include<stdio.h>
#include<iostream>
using namespace std;
//测试字符串
const char *S= "1234";
const int maxlen = strlen(S);
//为了学英语就试试用英语注释吧!
//let a char data insert in the designated pos of array
//the parmeter len is the lenght of the char data(Do not include '\0')
//Attations,in this funation does not check legitmacy!
void Insert(char* arr, int len,int pos,char ch) {
for (int i = len-1; i >= pos; i--) {
arr[i + 1] = arr[i];
}
arr[pos] = ch;
arr[len+1] = '\0';
}
//caculate the compound mode of char datas
//the result store in a vector,the parmeter lenght is how index where the string now i finish
//参数index表示现在我组合字符串的第几个元素了(从0算起),当长度为字符长度时,结束递归
void Combine(vector<char*>& v,int index) {
//当长度为0是,我将第一个char放到vector中
if (index == 0) {
char* tem = new char[index + 2]{ 0 };
tem[0] = S[0];
v.push_back(tem);
//加入下标为1的字符的组合方式
Combine(v, 1);
}
else if (index == maxlen)
{
return;
}
else {
char ch = S[index];
int vLen = v.size();
for (int i = 0; i < vLen; i++) {
//对于每一种组合,我要我有index+1种方式将这个字符插入到这个组合中
//就是遍历插入0-index共计index+1个下标
for (int k = 0; k < index +1; k++) {
char* tem = new char[index + 2]{0};
strcat_s(tem, index +2, v[0]);
Insert(tem, index, k, ch);
v.push_back(tem);
}
//这种方式组合完成之后就可以删除了
delete[] v[0];
v.erase(v.begin());
}
//进行加入下标为index-1的字符的组合方式
Combine(v, index + 1);
}
}
int main() {
vector<char*> v;
Combine(v, 0);
int len = v.size();
for (int i = 0; i <len ; i++) {
for (int k = 0; k < maxlen; k++) {
printf("%c", v[i][k]);
}
printf("\n");
delete[] v[i];
}
}