How can I find all permutations of a string without using recursion?(如何在不使用递归的情况下找到字符串的所有排列?)
问题描述
谁能帮我解决这个问题:这是一个查找任意长度字符串的所有排列的程序.需要相同的非递归形式.(首选C语言实现)
Can someone help me with this: This is a program to find all the permutations of a string of any length. Need a non-recursive form of the same. ( a C language implementation is preferred)
using namespace std;
string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute(string topermute, int place)
{
if(place == topermute.length() - 1)
{
cout<<topermute<<endl;
}
for(int nextchar = place; nextchar < topermute.length(); nextchar++)
{
permute(swtch(topermute, place, nextchar),place+1);
}
}
int main(int argc, char* argv[])
{
if(argc!=2)
{
cout<<"Proper input is 'permute string'";
return 1;
}
permute(argv[1], 0);
return 0;
}
推荐答案
基于堆栈的非递归等效代码:
A stack based non-recursive equivalent of your code:
#include <iostream>
#include <string>
struct State
{
State (std::string topermute_, int place_, int nextchar_, State* next_ = 0)
: topermute (topermute_)
, place (place_)
, nextchar (nextchar_)
, next (next_)
{
}
std::string topermute;
int place;
int nextchar;
State* next;
};
std::string swtch (std::string topermute, int x, int y)
{
std::string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute (std::string topermute, int place = 0)
{
// Linked list stack.
State* top = new State (topermute, place, place);
while (top != 0)
{
State* pop = top;
top = pop->next;
if (pop->place == pop->topermute.length () - 1)
{
std::cout << pop->topermute << std::endl;
}
for (int i = pop->place; i < pop->topermute.length (); ++i)
{
top = new State (swtch (pop->topermute, pop->place, i), pop->place + 1, i, top);
}
delete pop;
}
}
int main (int argc, char* argv[])
{
if (argc!=2)
{
std::cout<<"Proper input is 'permute string'";
return 1;
}
else
{
permute (argv[1]);
}
return 0;
}
我试图让它像 C 一样,并避免使用 c++ STL 容器和成员函数(不过为了简单起见,使用了构造函数).
I've tried to make it C-like and avoided c++ STL containers and member functions (used a constructor for simplicity though).
请注意,排列是按与原始顺序相反的顺序生成的.
Note, the permutations are generated in reverse order to the original.
我应该补充一点,以这种方式使用堆栈只是模拟递归.
I should add that using a stack in this way is just simulating recursion.
这篇关于如何在不使用递归的情况下找到字符串的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不使用递归的情况下找到字符串的所有排列?
基础教程推荐
- 使用scanf()读取字符串 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++ #define 1970-01-01
- C语言访问数组元素 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++定义类对象 1970-01-01
- C++按值调用 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- 初始化变量和赋值运算符 1970-01-01