题意:

image.png

解题思路:

  1. 思路:
  2. 动态规划
  3. 状态:定义dp[i][j]表示到达[i, j]位置的路径总和;
  4. 状态转移方程:dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
  5. 初始化(第一行和第一列只有一条路可走):dp[i][0] = 1; dp[0][j] = 1;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $m
  4. * @param Integer $n
  5. * @return Integer
  6. */
  7. function uniquePaths($m, $n) {
  8. $dp = [];
  9. for ($i = 0; $i < $m; $i++) $dp[0][$i] = 1;
  10. for ($i = 0; $i < $n; $i++) $dp[$i][0] = 1;
  11. for ($i = 1; $i < $n; $i++)
  12. for ($j = 1; $j < $m; $j++)
  13. $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1];
  14. return $dp[$n - 1][$m - 1];
  15. }
  16. function uniquePaths1($m, $n) {
  17. $memo = array_fill(0, $n, array_fill(0, $m, 0));
  18. $memo[0][0] = 1;
  19. return $this->helper1($m - 1, $n - 1, $memo);
  20. return helper(m, n);
  21. }
  22. function helper($m, $n) {
  23. //到达终点 总数 + 1
  24. if ($m == 1 && $n == 1) return 1;
  25. $res = 0;
  26. if ($m > 0) $res += $this->helper($m - 1, $n);
  27. if ($n > 0) $res += $this->helper($m, $n - 1);
  28. return $res;
  29. }
  30. function helper1($m, $n, $memo) {
  31. if ($m == 0 && $n == 0) return 1;
  32. if ($memo[$m][$n] != 0) return $memo[$m][$n];
  33. if ($m > 0) $memo[$m][$n] += $this->helper1($m - 1, $n, $memo);
  34. if ($n > 0) $memo[$m][$n] += $this->helper1($m, $n - 1, $memo);
  35. return $memo[$m][$n];
  36. }
  37. }

GO代码实现:

  1. func uniquePaths(m int, n int) int {
  2. if m <= 0 || n <= 0 {
  3. return 0
  4. }
  5. dp := make([][]int, m)
  6. for i := 0; i < m; i++ {
  7. dp[i] = make([]int, n)
  8. dp[i][0] = 1
  9. }
  10. for i := 0; i < n; i++ {
  11. dp[0][i] = 1
  12. }
  13. for i := 1; i < m; i++ {
  14. for j := 1; j < n; j++ {
  15. dp[i][j] = dp[i-1][j] + dp[i][j-1]
  16. }
  17. }
  18. return dp[m-1][n-1]
  19. }