简单算法--迭代/递归

关键词:动态规划   迭代  递归 


代码:

#include <iostream>

using namespace std;

unsigned int divCounterByRecursion(unsigned int n)
{
    if(n==1||n==2)
    {
        return 1;
    }
    else if(n==3)
    {
        return 2;
    }
    else if(n%2==0)
    {
        return divCounterByRecursion(n-1)+1;
    }
    else
    {
        return divCounterByRecursion(n-1);
    }
}

unsigned int divCounterByIteration(unsigned int n)
{
    unsigned int iConstantArr[]={0,1,1,2};
    if(n<=3)
    {
        return iConstantArr[n];
    }
    else
    {
        int iRes=iConstantArr[3];
        for(int i=4;i<=n;i++)
        {
            if(i%2==0)
            {
                iRes=iRes+1;
            }
        }
        return iRes;
    }
}


int main()
{
    cout << "Please input a number that not bigger than " << 0xffffffff <<endl;
    unsigned int n=-1;
    while(cin>>n)
    {
        if(n==0)
        {
            cout<<"Quit"<<endl;
            break;
        }
        cout<<"The result of divorce using the method below is byRecursion:"<<divCounterByRecursion(n)<<"  byIteration:"<<divCounterByIteration(n)<<endl<<endl;
    }
    return 0;
}


结果:



分析:

动态规划

        一种基于多分支递归的算法设计范式。其基本思想就是将问题分解为可以解决的简单的问题,最后基于这些已经解决的简单问题解决原始问题。

        Wikipedia动态规划

递归、迭代

        1、递归和迭代都是基于循环的,迭代是A不断调用B,递归是A不断调用A。

        2、递归也是迭代。递归都可以转化为迭代。

        3、递归逻辑清晰,代码简洁,但是效率低,因为有CPU保存现场的压栈出栈操作。

        4、迭代代码逻辑相对复杂,但是相对效率会更高。

        5、能用迭代的地方尽量用迭代,但是综合编译器优化等考虑,有些场合用递归更好,比如深度优先搜索。

        stackoverflow上关于递归和迭代/循环的比较的讨论



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值