用栈消除递归

1等值关系

“大问题“的函数值等于”小问题“的函数值的某种运算结果,例如求n!

/*用栈消除递归,以求n的阶乘为例*/
typedef struct node
{
    int n;
    int f;                //n对应的f(n)
    int flag;             //标志f(n)是否完成计算
}NodeType;

int fun(int n)
{
    stack<NodeType> st;
    NodeType e;
    e.n=n;
    e.flag=0;
    st.push(e);          

    while(!st.empty())
    {
        if(st.top().flag==0)               //对应的f尚未求出
        {
            if(st.top().n==1)              //到达递归出口
            {
                st.top().f=1;
                st.top().flag=1;
            }
            else                           //继续入栈
            {
                NodeType e1;
                e1.n=st.top().n-1;
                e1.flag=0;
                st.push(e1);
            }
            
        }

        else                              //f已经求出,出栈
        {
            NodeType e2;
            e2=st.top();
            st.pop();
            st.top().f=e2.f*st.top().n;
            st.top().flag=1;
        }   

        if(st.size()==1 && st.top().flag==1)     //栈pop到最后,只剩一个元素时,退出循环
            break; 
    }
    
    return st.top().f;
}

当然也可更简答地写为:

/*更简单的写法*/
int fun2(int n)
{
    stack<int> st;
    st.push(n);
    n--;
    while(n!=1)                      //入栈过程
    {
        st.push(n);
        n--;
    }

    int ret=1;
    while(!st.empty())              //出栈过程
    {
        ret=ret*st.top();
        st.pop();
    }
    return ret;
}
2.等价关系

等价关系是将”大问题“的求解过程转化为“小问题”求解得到,他们之间不是值的相等关系,而是解的等价关系,如Hanoi问题

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值