首页 > 解决方案 > 为在 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);

}

标签: c++

解决方案


问题不在于基本情况,只需将 for 循环条件更改为

i < permPart.length()

最后一个字符也应该与排列中的其他字符交换


推荐阅读