我需要制作一个程序来列出所有的排列组合。
有4个字符:
"1",
"2",
"R",
"T"
条件是,"R" 需要在它的前后有 "1",就像这样: 1-R-1
"T" 的条件是,它的后面必须是 "1" 或 "2",就像这样: T-1 或 T-2。
长度最多可以达到10
输出应该像这样:
111
112
121
122
1R1
1T1
1T2
211
212
221
222
2T1
2T2
T11
T12
T21
T22
我已经成功解决了排列问题,但是我无法让它们与条件配合使用。
void displayPermutation(string permutation[], int length){
int i;
for (i=0;i<length;i++){
cout<<permutation[i];
}
cout << endl;
}
void getPermutations(string operatorBank[], int operatorCount,
string permutation[],int permutationLength, int curIndex){
int i;
//stop recursion condition
if(curIndex == permutationLength){
displayPermutation(permutation,permutationLength);
}
else{
for(i = 0; i < operatorCount; i++){
permutation[curIndex] = operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
}
}
}
int main ()
{
int operatorCount = 4;
int permutationLength = 3;
string operatorBank[] = {"1","2","R","T"};
string permutation[] = {"","","",""}; //empty string
int curIndex = 0;
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex);
return 0;
}
permutationCount
不仅是要选择的项目数量,还包括字符的潜在“重复计数”?我问这个问题的原因是你说的第一项有效的是111
,即使1
在operatorBank
数组中只出现了一次。 - PaulMcKenzie