【LeetCode】路径系列

62. Unique Paths

题目:从左上到右下,有多少种不同的路径

思路:排列组合

public class Solution {
    public int uniquePaths(int m, int n) {
        long y = 1, x = 1;
        long min = Math.min(m, n);
        if(min == 1) return 1;
        for(long i = Math.max(m, n); i <= m+n-2; i++){
            y *= i;
        }
        for(long i = 1; i <= min-1; i++){
            x *= i;
        }
        return (int)(y/x);
    }
}
动态规划:
public class Solution {
public int uniquePaths(int m, int n) {
    int[][] grid = new int[m][n];
    for(int i = 0; i<m; i++){
        for(int j = 0; j<n; j++){
            if(i==0||j==0)
                grid[i][j] = 1;
            else
                grid[i][j] = grid[i][j-1] + grid[i-1][j];
        }
    }
    return grid[m-1][n-1];
}

63. Unique Paths II

题目:有1的位置表示有障碍,统计所有路径数

思路:沿用62题动态规划的方法,遇1路径数为零

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = obstacleGrid[0][0] == 1?0:1;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(i == 0 && j > 0){
                    if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
                    else dp[i][j] = dp[i][j-1];
                }
                if(j == 0 && i > 0){
                    if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
                    else dp[i][j] = dp[i-1][j];
                }
                if(i > 0 && j > 0){
                    if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
                    else dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        return dp[m-1][n-1];
    }
}

64. Minimum Path Sum

题目:找到最小路径和

思路:动态规划,很简单

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(i ==0 && j > 0) dp[i][j] = dp[i][j-1]+grid[i][j];
                if(j ==0 && i > 0) dp[i][j] = dp[i-1][j]+grid[i][j];
                if(i > 0 && j > 0) dp[i][j] = Math.min(dp[i][j-1], dp[i-1][j]) + grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }
}

70. Climbing Stairs

题目:爬梯子,每步1到2级,n步能爬到多少级

思路:斐波那契数列,没啥好说的

public class Solution {
    public int climbStairs(int n) {
        if(n < 2) return 1;
        int pre = 1;
        int x = 1;
        for(int i = 2; i <= n; i++){
            int next = pre+x;
            pre = x;
            x = next;
        }
        return x;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值