给定字符的排列算法,具有条件C++的重复
Algorithm for permutations of given characters with repetition with conditions C++
所以我需要制作一个列出所有排列的程序。
有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
时打印解决方案。在此步骤中,您还可以通过检查解决方案是否符合条件来检查解决方案是否有效。如果是你打印它,如果不是,你丢弃它。
这方面的策略是:
- 查找
R
并检查permutation[idx-1]
是否1
和permutation[idx+1]
是否1
- 查找
T
并检查permutation[idx+1]
是1
还是2
。
只有在满足这些条件时,您才能打印解决方案!
...
if(curIndex == permutationLength){
if (solutionValid()) {
displayPermutation(permutation,permutationLength);
}
}
...
- https://mathworld.wolfram.com/Permutation.html
- 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));
相关文章:
- 如何使用 soong 命名空间来有条件地编译模块
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 根据模板类型有条件地删除变量
- 有条件地选择带有 decltype() 和三元运算符的类型
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 有条件的打印和计数在 std::map 上有限制
- 如何在 c++ 中有条件地包含标头?
- 如何仅在Qt是用ltcg构建时才有条件地启用ltcg?
- 如何在Visual Studio 2019中有条件地编译c++源文件
- C++可以有条件地向下转换类指针吗
- 使用 SFINAE 有条件地解析分配器成员
- 有条件地删除宏
- 有条件地包含C++标准库
- 如何有条件地将元素添加到 std::array - C++11
- 是否根据编译器版本有条件地包含源文件
- 有条件地启用类C++构造函数
- 我可以有条件地使用多个参数吗?
- 有条件地使用 Boost Python 添加模块
- 有什么东西阻止std::optional::value_or()有条件地不例外吗?
- 无法使用三元运算符有条件地分配"istream &"?