LeetCode063 Unique Paths II

来源:互联网 发布:淘宝开直播需要交钱吗 编辑:程序博客网 时间:2024/05/30 02:53

详细见:leetcode.com/problems/unique-paths-ii


Java Solution: github

package leetcode;public class P063_UniquePathsII {public static void main(String[] args) {System.out.println(new Solution1().uniquePathsWithObstacles(new int[][] {{1},{0}}));}/* * 多次WA * 还是要注意逻辑的缜密 * 1 ms * 20.72%  */static class Solution1 {    public int uniquePathsWithObstacles(int[][] obstacleGrid) {    if (obstacleGrid == null || obstacleGrid[0] == null)    return 0;    int m = 0, n = 0;    if ((m = obstacleGrid.length) < 1 || (n = obstacleGrid[0].length) < 1)    return 0;        int[] route = new int[m];        route[0] = obstacleGrid[0][0] == 0 ? 1 : 0;        for (int j = 1; j < m; j ++)        route[j] = obstacleGrid[j][0] == 0 ? route[j - 1] : 0;        for (int i = 1; i < n; i ++) {        route[0] = obstacleGrid[0][i] == 0 ? route[0] : 0;        for (int j = 1; j < m; j ++)        route[j] = obstacleGrid[j][i] == 0 ? route[j] + route[j - 1] : 0;        }        return route[m - 1];    }}}


C Solution: github

/*    url: leetcode.com/problems/unique-paths-ii*/int uniquePathsWithObstacles(int** g, int m, int n) {    int* dp = (int*) malloc(sizeof(int) * n);    int i = 0, j = 0;    for (j = n-1; j > -1; j --) {        dp[j] = (j == n-1 || dp[j+1] == 1) && g[m-1][j] == 0 ? 1 : 0;    }    for (i = m-2; i > -1; i --) {        if (g[i][n-1] == 1) dp[n-1] = 0;        for (j = n-2; j > -1; j --) {            if (g[i][j] == 1) dp[j] = 0;            else dp[j] += g[i][j+1] == 1 ? 0 : dp[j+1];        }    }    i = dp[0];    free(dp);    return i;}


Python Solution: github

#coding=utf-8'''    url: leetcode.com/problems/unique-paths-ii    @author:     zxwtry    @email:      zxwtry@qq.com    @date:       2017年4月13日    @details:    Solution: 66ms 18.15%'''class Solution(object):    def uniquePathsWithObstacles(self, g):        """        :type g: List[List[int]]        :rtype: int        """        if g == None or g[0] == None: return 0        m = len(g)        n = len(g[0])        dp = [0] * n        for j in range(n-1, -1, -1):            if j == n-1 or dp[j+1] == 1:                if g[m-1][j] == 0:                    dp[j] = 1                    continue            dp[j] = 0        for i in range(m-2, -1, -1):            if g[i][n-1] == 1: dp[n-1] = 0            for j in range(n-2, -1, -1):                if g[i][j] == 1: dp[j] = 0                else:dp[j] += 0 if g[i][j+1] == 1 else dp[j+1]        return dp[0]



0 0