前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 62. Unique Paths

leetcode: 62. Unique Paths

作者头像
JNingWei
发布2018-09-27 17:05:31
3590
发布2018-09-27 17:05:31
举报

Problem

# A robot is located at the top-left corner of a m x n grid 
# (marked 'Start' in the diagram below).
#
# The robot can only move either down or right at any point in time. 
# The robot is trying to reach the bottom-right corner of the grid 
# (marked 'Finish' in the diagram below).
#
# How many possible unique paths are there?
这里写图片描述
这里写图片描述
# Note: m and n will be at most 100.

Idea

DP算法。
Climbing Stairs二维版。计算解个数的题多半是用DP。

dp[i][j]表示从起点到位置(i, j)的路径总数。
DP题目定义好状态后,接下去有两个任务:找通项公式,以及确定计算的方向。

1. 由于只能向右和左走,所以对于(i, j)来说,只能从左边或上边的格子走下来:
    dp[i][j] = dp[i-1][j] + dp[i][j-1]
2. 对于网格最上边和最左边,则只能从起点出发直线走到,dp[0][j] = dp[i][0] = 1
3. 计算方向从上到下,从左到右即可。可以用滚动数组实现。
4. 为了节省空间,我们使用一维数组dp,一行一行的刷新也可以。

AC

DP:

class Solution():
    def uniquePaths(self, m, n):
        ways = [1] * m
        for _ in range(1, n):
            for j in range(1, m):
                ways[j] += ways[j - 1]
        return ways[-1]


if __name__ == "__main__":
    assert Solution().uniquePaths(2, 1) == 1
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
    • Idea
    • AC
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档