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

  • 相关阅读:
    OpenCMS创建导航条
    C++笔记(2)面向对象编程
    C++笔记(3)模板与泛型编程
    多线程和信号量
    C++笔记(4)用于大型程序的工具
    C++笔记(5)特殊工具与技术
    C++笔记(1)类
    Effective C++ 笔记(1)
    C语言笔记整理(2)
    C语言笔记整理(3)
  • 原文地址:https://www.cnblogs.com/chruny/p/5008277.html
Copyright © 2011-2022 走看看