LeetCode 62. 不同路径

题目地址:https://leetcode-cn.com/problems/unique-paths/description/

思路:递归或者动态规划

超时代码:

class Solution {
    public int uniquePaths(int m, int n) {
        // 在网格边界的格子只能有一种走法
        if (m == 1 || n == 1) {
            return 1;
        }
        // m,n这个位置只能从(m - 1 , n)和(m, n - 1)移动而来
        return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
    }
}

备忘录法

class Solution {
    
    public static int[][] grid = new int[110][110];

    public int uniquePaths(int m, int n) {
        if (grid[m][n] != 0)
            return grid[m][n];
        if (m == 1 || n == 1) {
            return 1;
        }
        return grid[m][n] = uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
    }
}

动态规划

class Solution {

    public static int[][] grid = new int[110][110];

    public int uniquePaths(int m, int n) {

        for (int i = 1; i <= n ; i++) {
            for (int j = 1; j <= m ; j++) {
                if (i == 1 || j == 1)
                    grid[i][j] = 1;
                else
                    grid[i][j] = grid[i][j-1] + grid[i-1][j];
            }
        }
        return grid[n][m];
    }
}

 

你可能感兴趣的:(LeetCode)