【LeetCode】No.62. Unique Paths -- Java Version

76 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情.

题目链接: leetcode.com/problems/un…

1. 题目介绍(Unique Paths)

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

【Translate】: 在mx n网格上有一个机器人,机器人最初位于左上角(即grid[0][0]),机器人试图移动到右下角(即grid[m - 1][n - 1])。请注意机器人在任何时间点只能向下或向右移动。

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

【Translate】: 给定两个整数m和n,返回机器人到达右下角可能的唯一路径的数量。

The test cases are generated so that the answer will be less than or equal to 2 * 109.

【Translate】: 生成测试用例,因此答案将小于或等于2 * 109。

【测试用例】:

testcase1 testcase2

【约束】:

Constraints

2. 题解

2.1 数学解

原题解来自于whitehat的 Math solution, O(1) space。该题为一个组合问题,以3x7 矩阵为例,机器人需要采取 2+6 = 8 步,其中 2 步向下,6 步向右,顺序不限,这就直接转化成了排列组合问题,那么Total permutations = (m+n)! / (m! * n!)=C(8,2)。

public class Solution {
    public int uniquePaths(int m, int n) {
        if(m == 1 || n == 1)
            return 1;
        m--;
        n--;
        if(m < n) {              // Swap, so that m is the bigger number
            m = m + n;
            n = m - n;
            m = m - n;
        }
        long res = 1;
        int j = 1;
        for(int i = m+1; i <= m+n; i++, j++){       // Instead of taking factorial, keep on multiply & divide
            res *= i;
            res /= j;
        }
            
        return (int)res;
    }
}

case1

2.2 DP

原题解来自于zeller2的 Clean and simple DP java,非常简洁明了,典型的DP。

public class Solution {
    public int uniquePaths(int m, int n) {
        int[][] grid = new int[m][n];
        for(int i = 0; i<m; i++){
            for(int j = 0; j<n; j++){
                if(i==0||j==0)
                    grid[i][j] = 1;
                else
                    grid[i][j] = grid[i][j-1] + grid[i-1][j];
            }
        }
        return grid[m-1][n-1];
    }
}

case2