zoukankan      html  css  js  c++  java
  • [LeetCode] 62. Unique Paths(不同的路径)

    Description

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
    一只机器人位于 m x n 方格的左上角(下图中以“Start”标识)。

    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).
    机器人只能向下或向右移动。该机器人欲抵达方格的右下角(下图中以“Finish”标识)。

    How many possible unique paths are there?
    有多少种不同的路径?

    Examples

    Example 1

    Input: m = 3, n = 7
    Output: 28
    

    Example 2

    Input: m = 3, n = 2
    Output: 3
    Explanation:
    From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
    1. Right -> Down -> Down
    2. Down -> Down -> Right
    3. Down -> Right -> Down
    

    Example 3

    Input: m = 7, n = 3
    Output: 28
    

    Example 4

    Input: m = 3, n = 3
    Output: 6
    

    Constraints

    • 1 <= m, n <= 100

    • It's guarranteed that the answer will be less than or equal to 2 * 10^9.

    Solution

    动态规划例题之二,状态转义方程如下:

    [ exttt{dp(i, j)} = egin{cases} 1, &i = 0 或j = 0\ exttt{dp(i - 1, j)} + exttt{dp(i, j - 1)}, &else end{cases} ]

    其中 dp(i, j) 表示 (i, j) 时可能的路径数

    class Solution {
        fun uniquePaths(m: Int, n: Int): Int {
            val dp = Array(m) { IntArray(n) }
            (0 until m).forEach { dp[it][0] = 1 }
            (0 until n).forEach { dp[0][it] = 1 }
    
            for (i in 1 until m) {
                for (j in 1 until n) {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
                }
            }
    
            return dp.last().last()
        }
    }
    
  • 相关阅读:
    break语句和continue语句
    switch注意事项
    运算符优先级
    混合赋值运算符做算数运算时不改变自身数据类型
    arpspoof+ettercap嗅探局域网HTTP/HTTPS账号密码
    linux上chrome、vlc等程序root不能运行的解决办法
    kalilinux、parrotsecos没有声音
    linux相关文章链接
    live kalilinux能保存文件和设置
    渗透测试文章链接
  • 原文地址:https://www.cnblogs.com/zhongju/p/13943685.html
Copyright © 2011-2022 走看看