首页 > 其他 > 详细

慎用递归!

时间:2014-06-01 11:32:29      阅读:352      评论:0      收藏:0      [点我收藏+]

其一,所有的递归实现都可以 iteratively 实现,虽然很多时候递归的代码更简洁。

其二,递归会产生多余的开销,包括空间和时间。

其三,如果一定要递归,不要在一个递归函数里做多件事,最好只做一件。

像下面的代码(未完成,因为写不下去了),试图在递归函数里做三件事,

(1) 检测路径是否存在

(2) 构造路径

(3) 处理cache

所以写到这个地步逻辑已经非常混乱了。

bubuko.com,布布扣
public boolean getPath(int x, int y, ArrayList<Point> path,
            HashMap<Point, Boolean> cache){
        
        if(!isFree(x, y)){
            return false;
        }

        // in the code below,
        // we are guaranteed point (x, y) is free
        
        Point p = new Point(x, y);
        
        if(x == 0 && y == 0){
            path.add(p);
            return true;
        }
        
        if(x >= 1 && getPath(x -1, y, path) ){
            path.add(p);
            return true;
        }
        
        if(y >= 1 && getPath(x, y-1, path)){
            path.add(p);
            return true;
        }
        return false;
    }
bubuko.com,布布扣

 

慎用递归!,布布扣,bubuko.com

慎用递归!

原文:http://www.cnblogs.com/Antech/p/3763026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!