• 慎用递归!


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

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

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

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

    (1) 检测路径是否存在

    (2) 构造路径

    (3) 处理cache

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

    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;
        }
  • 相关阅读:
    python3 网络编程
    python3 字典及其方法
    洛谷P2239 螺旋矩阵
    洛谷P4281 紧急会议
    洛谷 P4427 求和
    树的直径
    洛谷P3398 仓鼠找suger
    洛谷P3865 ST表
    洛谷P1638逛画展
    洛谷P1886 滑动窗口
  • 原文地址:https://www.cnblogs.com/Antech/p/3763026.html
Copyright © 2020-2023  润新知