zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):063-Unique Paths II

    题目来源:

      https://leetcode.com/problems/unique-paths-ii/


    题意分析:

      这题的规则和上一题一样。给一个m×n的矩阵0,1矩阵。0代表可以经过,1代表不可以通过。返回从(0,0)到(m,n)一共有多少种走法。


    题目思路:

      这题如果还是用组合的方法做将会非常复杂,所以组合的方法不再考虑。不难发现,从(0,0)到(i,j)的所有可能等于(0,0)到(i - 1,j)和(0,0)到(i,j-1)的和。那么建立一个m×n的表a,a[i][j]代表(0,0)到(i,j)的走法。把表填满,就可以得到结果。时间复杂度是O(m×n)


    代码(python):

      

     1 class Solution(object):
     2     def uniquePathsWithObstacles(self, obstacleGrid):
     3         """
     4         :type obstacleGrid: List[List[int]]
     5         :rtype: int
     6         """
     7         m,n = len(obstacleGrid),len(obstacleGrid[0])
     8         ans = [[0 for i in range(n)] for j in range(m)]
     9         ans[0][0] = 1
    10         for i in range(m):
    11             for j in range(n):
    12                 if obstacleGrid[i][j] == 1:
    13                     ans[i][j] = 0
    14                 elif i != 0 and j == 0:
    15                     ans[i][j] = ans[i - 1][j]
    16                 elif i == 0 and j != 0:
    17                     ans[i][j] = ans[i][j - 1]
    18                 elif i != 0 and j != 0:
    19                     ans[i][j] = ans[i -1][j] + ans[i][j - 1]
    20         return ans[m - 1][n - 1]
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5008277.html

  • 相关阅读:
    向Url发送post请求传递参数
    表格列转行
    C#匹配HTML中的图片地址
    C# 正则表达式(备忘录)
    将天文数字转换成中文大写
    搜索引擎优化排名因素小结
    WPF概述
    将中文汉字转换成拼音(全拼)
    提取网页中的链接并生成xml
    快速排序算法的实现
  • 原文地址:https://www.cnblogs.com/chruny/p/5008277.html
Copyright © 2011-2022 走看看