给定字符的排列算法,具有条件C++的重复

Algorithm for permutations of given characters with repetition with conditions C++

本文关键字:C++ 有条件 算法 字符 排列      更新时间:2023-10-16

所以我需要制作一个列出所有排列的程序。
有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;
}

你的术语有点混乱。你说的不是排列[1],而是组合[2]。

据我所知,您已经有了算法(递归回溯(,您只是没有通过过滤解决方案空间来检查您的解决方案是否有效。因此,您在不考虑任何约束的情况下生成所有解决方案,并在到达permutationLength时打印解决方案。在此步骤中,您还可以通过检查解决方案是否符合条件来检查解决方案是否有效。如果是你打印它,如果不是,你丢弃它。

这方面的策略是:

  1. 查找R并检查permutation[idx-1]是否1permutation[idx+1]是否1
  2. 查找T并检查permutation[idx+1]1还是2

只有在满足这些条件时,您才能打印解决方案!

...
if(curIndex == permutationLength){
if (solutionValid()) {
displayPermutation(permutation,permutationLength);
}
}
...
  1. https://mathworld.wolfram.com/Permutation.html
  2. https://mathworld.wolfram.com/Combination.html

你的意思是这样的递归吗?

function f(n, str=""){
if (!n)
return [str];

let result = [];

if (n >= 3)
result = result.concat(f(n - 3, str + "1R1"));

if (n >= 2)
result = result
.concat(f(n - 2, str + "T1"))
.concat(f(n - 2, str + "T2"));

return result
.concat(f(n - 1, str + "1"))
.concat(f(n - 1, str + "2"));
}
console.log(f(3));