最一开始直接用dfs recursion暴力遍历出所有的route,但是超时不给过TLE了
然后去网上搜索解法发现可以结合缓存,保留一个f[m][n]数组把遍历到的点的path数保存到数组里,下次再走到这一点就不需要再递归调用dfs来找值啦。参考了此reference中dfs+缓存的做法:
https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dfs/unique-paths.html
最终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;
}
}