【发布时间】:2019-12-10 11:43:16
【问题描述】:
我已经编写了有关如何使用 for 循环查找给定字符串的排列的代码。我遵循了教授的伪代码,但不确定如何将其转换为递归。 (不适用于、goto、while、STL 算法)。
void perms(string prefix, string rest)
{
// Followed Format of Pseudocode that Professor gave us
// If nothing remains in the rest string cout what we have for prefix
if (rest == "")
{
cout << prefix << endl;
}
else
{
for (int i = 0; i < rest.length(); i++)
{
string prefix2 = prefix + rest[i];
string rest2 = rest.substr(0, i) + rest.substr(i + 1);
perms(prefix2, rest2);
}
}
}
代码运行良好,只是需要帮助将其转换为递归。
【问题讨论】:
-
呃?它在我看来已经是递归的了。
-
这仍然是一个递归解决方案,因为您在 printpermutations 内部调用 printPermutations。您是否正在寻找不使用 for 循环的递归解决方案?您在这里有一个递归步骤和一个基本案例,基本上是您需要确定它是否递归的两件事
-
我们不允许使用任何类型的循环,我们只允许使用 if 语句 :( 我使用 for 循环编写它,因为我不知道如何只使用 if声明。
-
您能否提供一个示例输入和所需的输出?
-
会的! @李子0
标签: c++ string recursion permutation