[LeetCode] 62. Unique Paths

[LeetCode] 62. Unique Paths

题目描述

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

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).

How many possible unique paths are there?

分析

这个是一个经典的排列组合问题,可以转换为一个走m+n-2步,其中m-1步向下走,一共有多少种走法。
开始想直接计算组合数,但是在test case:[51, 9]中变成了负数,应该是溢出了,改为使用dp计算。
直接计算组合数:

class Solution {
public:
  int uniquePaths(int m, int n) {
    if (m == 1 || n == 1) return 1;
    int step = m + n - 2;
    if (n > m) {
      int temp = n;
      n = m;
      m = temp;
    }
    int count = 1;
    for (int i = 1; i < n; i++) {
      count *= step;
      count /= i;
      step--;
    }
    return count;
  }
};

使用dp:

class Solution {
public:
  int uniquePaths(int m, int n) {
    int dp[m][n];
    for (int i = 0; i < n; i++) {
      dp[0][i] = 1;
    }
    for (int i = 0; i < m; i++) {
      dp[i][0] = 1;
    }
    for (int i = 1; i < m; i++) {
      for (int j = 1; j < n; j++) {
        dp[i][j] = dp[i-1][j] + dp[i][j-1];
      }
    }
    return dp[m-1][n-1];
  }
};

猜你喜欢

转载自blog.csdn.net/weixin_39629939/article/details/79047821