Recursive method(递归方法)




<strong><span style="font-size:18px;color:#3333ff;"> The easiest way to write a recursive method is to strictly follow a pattern:</span></strong>
Result M(Problem prob)
{
    if (<problem can be solved easily>)
        return <easy solution>;
    // The problem cannot be solved easily.
    Problem smaller1 = <reduce problem to smaller problem>
    Result result1 = M(smaller1);
    Problem smaller2 = <reduce problem to smaller problem>
    Result result2 = M(smaller2);
    ...
    Result finalResult = <combine all results of smaller problem to solve large problem>
    return finalResult;
}


So suppose you want to solve the problem "what is the maximum depth of my binary tree?" 

int Depth(Tree tree)
{
    // Start with the trivial case. Is the tree empty?
    if (tree.IsEmpty) return 0;
    // The tree is not empty. 
    // Reduce the problem to two smaller problems and solve them:
    int depthLeft = Depth(tree.Left);
    int depthRight = Depth(tree.Right);
    // Now combine the two solutions to solve the larger problem.
    return Math.Max(depthLeft, depthRight) + 1;
}

You need three things to make recursion work:

  • The problem has to get smaller every time you recurse.
  • The problem has to eventually get so small that it can be solved without recursion
  • The problem has to be solvable by breaking it down into a series of smaller problems, solving each one, and combining the results.

If you cannot guarantee those three things then do not use a recursive solution.


百家之言:

首先是思想方法上要转变,不要试图解决问题(这是常规的思考方式),而应该“鼠目寸光”地只想解决一点点,要点是,解决一点点之后,剩下来的问题还是原来的问题,但规模要比原问题小了。

    当你的问题分析透彻,何时使用递归就会自然明了。递归只是一种函数调用的技巧,不是解决问题的公式。一个问题可以用递归做,也可以不用递归做,递归不是必须的。所以,理解你需要解决的问题,想清楚解决问题的步骤方法,你会突然发现,原来可以用递归来简化问题。不要一开始就想着如何用递归。

    其实递归和循环是等价的,你可以用循环解决的问题,都可以用递归来解决。也就是说,你可以尝试着观察自己所写过的使用了循环结构的代码,然后试图对它们进行一个``定义上''的归纳,比如一个数的阶乘的计算方法是n*(n-1)*...*2*1,它的定义可以想成是n*(n-1)!,这样,你就把一个循环变成了一个递归了。只要练习多了,你就会自然而然地用递归的方式来想问题了。关键一点就是:

_循环_要求你思考一件事情_怎么做_,而_递归_要求你思考一件事情_怎么定义_。这是我的理解~

    刷题目,图的广度、深度遍历、动态规划等等,刷个几十道。

     个人感觉和建议,有2点:

  1. 写出递归函数也就是要处理好递归的3个主要的点: a)出口条件,即递归“什么时候结束”,这个通常在递归函数的开始就写好; b) 如何由"情况 n" 变化到"情况 n+1", 也就是非出口情况,也就是一般情况——"正在"递归中的情况; c) 初始条件,也就是这个递归调用以什么样的初始条件开始
  2. 可以说,上述a,b,c三个条件组成了我们的递归函数;解决好上述3点,也就很容易地写出一个递归

   试着在脑子里跑代码,看着程序,一行一行的看,脑子存着一个一个的中间变量,跟着变。

   然后,跑上几个来回以后,离开程序,纯粹在脑子里跑。

   从最简单的递归开始,比如计算斐波那契数列的递归。甚至,仅仅是计算阶乘的递归。





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值