写的一个递归程序 出问题了

fx397993401 2012-03-16 09:36:27


大致的是 给定 1 2 3 4 到n 的序列
求出所有的合法的出站序列

准备用递归写
a 表示 初始站 b 是中间的那个中转站 c 是终点

foo(m,n) //表示 a 和 b 中元素的个数
有两种转移方式 --》foo(m,n-1)

--> foo(m-1,n+1)

但是我一直不太会控制 这个递归程序,貌似数据会有污染


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stack>
#include <iostream>

using namespace std;
const int N = 1000;

int a[N],d[N];
stack<int> b,c;
int M;

//void cp(stack<int> &src ,)

void foo(int n,int m)
{
int tmp = 0;
if(m < 0 || n <0 )
return ;
if(m == 0 && n ==0)
{
int i = 1;
while(!c.empty() )
{
tmp = c.top();
c.pop();
d[i++] = tmp;
}
for(i = M ; i > 0 ; i --)
{
printf("%d%c",d[i],(i==1)?'\n':' ');
c.push(d[i]); //恢复栈C 的内容
}

}
if(n > 0)
{
tmp = a[n];
b.push(tmp);
foo(n-1,m+1);
b.pop();
}

if( m >0 && !b.empty())
{
tmp = b.top();
b.pop();
c.push(tmp);
foo(n,m-1);
c.pop();
}

}

int main()
{
M = 4;
for(int i = 1 ; i <= M ; i ++)
a[i] = i;

foo(M,0);

return 0;
}


...全文
157 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
i_love_ai 2012-03-23
  • 打赏
  • 举报
回复
来晚了,不过还是关注一下。
fx397993401 2012-03-19
  • 打赏
  • 举报
回复
确实 如此 十分感谢 ,

[Quote=引用 2 楼 thefirstz 的回复:]

数据出栈以后,记得把数据再送回来,以便下次递归时候使用,在楼主代码中增加了2条语句,我标识在程序中了
C/C++ code

const int N = 1000;
int a[N],d[N];
stack<int> b,c;
int M;

void foo(int n,int m)
{
int tmp = 0;
if(m < 0 || n <0 )
ret……
[/Quote]
昵称很不好取 2012-03-18
  • 打赏
  • 举报
回复
数据出栈以后,记得把数据再送回来,以便下次递归时候使用,在楼主代码中增加了2条语句,我标识在程序中了

const int N = 1000;
int a[N],d[N];
stack<int> b,c;
int M;

void foo(int n,int m)
{
int tmp = 0;
if(m < 0 || n <0 )
return ;
if(m == 0 && n ==0)
{
int i = 1;
while(!c.empty() )
{
tmp = c.top();
c.pop();
d[i++] = tmp;
}
for(i = M ; i > 0 ; i --)
{
printf("%d%c",d[i],(i==1)?'\n':' ');
c.push(d[i]); //恢复栈C 的内容
}

}
if(n > 0)
{
tmp = a[n];
b.push(tmp);
foo(n-1,m+1);
a[n] = b.top(); //这里增加一句,需要再次把数据复原,以便下次使用
b.pop();
}

if( m >0 && !b.empty())
{
tmp = b.top();
b.pop();
c.push(tmp);
foo(n,m-1);
b.push(c.top()); //相应的,这里添加一句
c.pop();
}

}

int main()
{
M = 4;
for(int i = 1 ; i <= M ; i ++)
a[i] = i;

foo(M,0);

return 0;
}

JackBurd 2012-03-17
  • 打赏
  • 举报
回复
你最好不要将C和C++语法混用,下面是我写的,希望对你用帮助。

#include<iostream>
#include<stack>

using namespace std;
int count = 0;

template<class T>
void Create(stack<T> S, T tar[], T str[], int pos, int curp, int n)
{
if(pos < n) //还有元素没进栈则继续进栈
{
S.push(str[pos]); //进栈
Create(S, tar, str, pos+1, curp, n);
S.pop(); //出栈恢复环境
}

if(!S.empty()) //栈不为空则继续出栈
{
tar[curp] = S.top();//将出栈元素记录到目标数组中以待输出
S.pop(); //出栈
Create(S, tar, str, pos, curp+1, n);
S.push(tar[curp]); //进栈恢复环境
}

if(pos == n && S.empty()) //栈空且所有元素都进过栈则输出
{
cout << "[" << ++count << "] ";
for(int i = 0; i < curp; i ++)
{
cout << tar[i];
}
cout << endl;
}
}

void main()
{
stack<char> S;
char str[6] = "12345";
char tar[6];

Create(S, tar, str, 0, 0, 5);
}

33,009

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧