一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径?
例如,上图是一个7 x 3 的网格。有多少可能的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2输出: 3解释:从左上角开始,总共有 3 条路径可以到达右下角。1. 向右 -> 向右 -> 向下2. 向右 -> 向下 -> 向右3. 向下 -> 向右 -> 向右示例 2: 输入: m = 7, n = 3输出: 28 思路: 1. dp
dp[i][j] = dp[i-1]+dp[j-1] 2.排列组合 机器人到达终点向下,或者向右的个数是固定的,比如,7X3的,向下2次,向右6次,只是通过不同自由组合 C(m+n-2,m-1) 3.回溯(超时) *dp代码*
1 class Solution67 { 2 3 public int uniquePaths(int m, int n) { 4 int[][] dp = new int[m][n]; 5 for (int i = 0; i < m; i++) { 6 dp[i][0] = 1; 7 } 8 for (int i = 0; i < n; i++) { 9 dp[0][i] = 1; 10 } 11 12 for (int i = 1; i < m; i++) { 13 for (int j = 1; j < n; j++) { 14 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 15 } 16 } 17 return dp[m - 1][n - 1]; 18 } 19 }
原文地址:https://www.cnblogs.com/rainbow-/p/10351236.html
时间: 2024-08-01 20:42:39