c++ - 为在 C++ 中打印出给定字符串的所有排列的递归程序编写基本案例
问题描述
该函数被称为: Perm( "xyz", "abc" ); 然后它将打印:
xyzabc xyzacb xyzbac xyzbca xyzcab xyzcba xyz 是固定的,并且将 abc 的所有排列连接到它。
我开始了一个 for 循环来处理一般情况和部分基本情况,但我很难弄清楚我哪里出错了。
#include <string>
#include <iostream>
using namespace std;
void Perm(string fixedPart, string permPart)
{
if (permPart.length() == 1) {
cout << fixedPart << permPart << endl;
}
else {
for (int i = 0; i < permPart.length() - 1; i++) {
Perm(fixedPart + permPart[i] ,
permPart.substr(0, i) + permPart.substr(i + 1,permPart.length()-1));
}
}
}
int main(){
// Don't touch main!!!
string s;
cout << "Enter a String: ";
cin >> s;
cout << s << endl;
cout << "Perms are: " << endl;
Perm("xyz", s);
}
解决方案
问题不在于基本情况,只需将 for 循环条件更改为
i < permPart.length()
最后一个字符也应该与排列中的其他字符交换
推荐阅读
- angularjs - ng-class 属性不适用于指令但适用于原始代码?
- java - 如何通过 Selenium 验证鼠标悬停时是否突出显示星级
- java - CardView 展开后自动滚动
- image - 从带有扩展名的 FB Graph API 检索有效的照片 URL
- neo4j - Neo4j db.schema() 通过 API
- azure - How can I see all functions in the on-prem functions portal
- regex - Power shell 的正则表达式协助 - 过滤并显示正确的信息
- sql - 加入没有关系的表
- google-apps-script - 检查电子邮件在 Google Apps 脚本中是否有效
- android - 带有改造的 HTTP 请求字符集