Leetcode 62. Unique Paths

最一开始直接用dfs recursion暴力遍历出全部的route,可是超时不给过TLE了html

而后去网上搜索解法发现能够结合缓存,保留一个f[m][n]数组把遍历到的点的path数保存到数组里,下次再走到这一点就不须要再递归调用dfs来找值啦。参考了此reference中dfs+缓存的作法:java

https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dfs/unique-paths.htmlgit

最终AC的code以下:数组

//int cnt = 0;//不须要计这个数,直接用返回值和加法来记录步数便可
    private int[][] f; //cache of number of paths to (x,y) point 
    public int uniquePaths(int m, int n) {
        f = new int[m][n];
        f[m-1][n-1] = 1;
        return dfs(0,0,m,n);
    }
    //此dfs返回的是从(row,col)到goal即(m-1,n-1)有多少条path能够走
    public int dfs(int row, int col, int m, int n) {
        if(row==m-1&&col==n-1) {
            //cnt ++;
            return 1;
        }
        if(row>m-1||col>n-1) {
            return 0;
        }
        if(f[row][col]>0) {//若是path上的点以前已被走过(缓存过)则不须要再recursively调用dfs()函数,直接返回缓存的值
            return f[row][col];
        }
        else {
            int paths = dfs(row+1,col,m,n)+dfs(row,col+1,m,n);
            if(row+1<m&&col+1<n) f[row][col] = paths;
            return paths;
        }
        
    }
相关文章
相关标签/搜索