【发布时间】:2015-10-16 11:16:17
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word;
cin>>word;
int s = word.size();
string original_word = word;
do
{
for(decltype(s) i =1; i!= s;++i){
auto temp =word[i-1];
word[i-1] = word[i];
word[i] = temp;
cout<<word<<endl;
}
}while(word!=original_word);
}
此解决方案是否有效?通过递归执行此解决方案的效果如何?
编辑:当我测试程序时,它显示了所有排列 即猫生产: 猫 行为 atc tac tca cta
【问题讨论】:
-
我会比较它与使用
std::next_permutation() -
从考虑正确性开始,而不是效率。上面的代码不可能生成所有的排列。
-
这需要 2 * s^2 时间。 (它会将第一个字母冒泡到列表的末尾)。它基本上会显示需要反转单词然后反转反转单词的步骤。这并没有给你所有的排列。你至少需要(s!时间来找到这个词的所有排列)。我建议只在字符串上使用
std::next_permutation()。这是正确的,它应该是相当有效的。 -
here 一个演示,其中您的代码显示缺少排列:1342、1324、1432... 丢失。
标签: c++ string performance c++11 permutation