【Lintcode】115. Unique Paths II

题目地址:

https://www.lintcode.com/problem/unique-paths-ii/description

给定一个二维 0 1 0-1 矩阵, 0 0 代表空地, 1 1 代表障碍物。从左上走到右下,每次只能向右或向下走一步,不能走到障碍物上也不能走出界,问一共有多少种不同走法。

可以用动态规划,按照最后一步是从上面走下来还是从左走到右来分类即可,可以用滚动数组来做空间优化,每一行都从左向右计算即可。代码如下:

public class Solution {
    /**
     * @param obstacleGrid: A list of lists of integers
     * @return: An integer
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // write your code here
        if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[0][0] == 1) {
            return 0;
        }
        
        int[] dp = new int[obstacleGrid[0].length];
        dp[0] = 1;
        for (int i = 1; i < obstacleGrid[0].length; i++) {
            dp[i] = obstacleGrid[0][i] == 1 ? 0 : dp[i - 1];
        }
    
        for (int i = 1; i < obstacleGrid.length; i++) {
            for (int j = 0; j < obstacleGrid[0].length; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[j] = 0;
                } else if (j > 0) {
                    dp[j] += dp[j - 1];
                }
            }
        }
        
        return dp[dp.length - 1];
    }
}

时间复杂度 O ( m n ) O(mn) ,空间 O ( n ) O(n) m m 为矩阵的宽, n n 为长。

发布了388 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105427704