LeetCode063 Unique Paths II

详细见: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值