|
| 1 | +package com.bytecode.leetcode.dp; |
| 2 | + |
| 3 | +/** |
| 4 | + * 62. Unique Paths |
| 5 | + * <p> |
| 6 | + * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). |
| 7 | + * <p> |
| 8 | + * 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). |
| 9 | + * <p> |
| 10 | + * How many possible unique paths are there? |
| 11 | + * <p> |
| 12 | + * <p> |
| 13 | + * Above is a 7 x 3 grid. How many possible unique paths are there? |
| 14 | + * <p> |
| 15 | + * Note: m and n will be at most 100. |
| 16 | + * <p> |
| 17 | + * Example 1: |
| 18 | + * <p> |
| 19 | + * Input: m = 3, n = 2 |
| 20 | + * Output: 3 |
| 21 | + * Explanation: |
| 22 | + * From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: |
| 23 | + * 1. Right -> Right -> Down |
| 24 | + * 2. Right -> Down -> Right |
| 25 | + * 3. Down -> Right -> Right |
| 26 | + * Example 2: |
| 27 | + * <p> |
| 28 | + * Input: m = 7, n = 3 |
| 29 | + * Output: 28 |
| 30 | + * <p> |
| 31 | + * <a href="https://leetcode.com/problems/unique-paths/">62. Unique Paths</a> |
| 32 | + * <p> |
| 33 | + * <a href="https://leetcode-cn.com/problems/unique-paths/">62. 不同路径</a> |
| 34 | + * <p> |
| 35 | + * Created by vencial on 2019-09-10. |
| 36 | + */ |
| 37 | +public class UniquePaths { |
| 38 | + |
| 39 | + /** |
| 40 | + * 1. 设dp为每格可能路径的总数, 则第一行和第一列均为1 |
| 41 | + * 2. dp[i][j]则为dp[i - 1][j] 加上dp[i][j - 1]的总和 |
| 42 | + * <p> |
| 43 | + * 1. let dp is the sum of possible unique paths, as we know dp of the first row and column is 1 |
| 44 | + * 2. dp[i][j] is the sum of left dp and the top dp, that is dp[i - 1][j] + dp[i][j - 1] |
| 45 | + * |
| 46 | + * @param m m |
| 47 | + * @param n n |
| 48 | + * @return int |
| 49 | + */ |
| 50 | + public int uniquePaths(int m, int n) { |
| 51 | + int dp[][] = new int[m][n]; |
| 52 | + dp[0][0] = 0; |
| 53 | + for (int i = 0; i < m; i++) { |
| 54 | + dp[i][0] = 1; |
| 55 | + } |
| 56 | + for (int i = 0; i < n; i++) { |
| 57 | + dp[0][i] = 1; |
| 58 | + } |
| 59 | + for (int i = 1; i < m; i++) { |
| 60 | + for (int j = 1; j < n; j++) { |
| 61 | + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; |
| 62 | + } |
| 63 | + } |
| 64 | + return dp[m - 1][n - 1]; |
| 65 | + } |
| 66 | +} |
0 commit comments