LeetCode——Unique Paths

Question

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?

Note: m and n will be at most 100.

Solution 1

动态规划,到(i, j)的所有方法等于到(i - 1, j)加上(i, j - 1)。

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

Solution 2

组合数学中的格路问题,注意要边乘边除,不然要越界。

class Solution {
    public:
        int uniquePaths(int m, int n) {
            int N = n + m - 2;// how much steps we need to do
            int k = m - 1; // number of steps that need to go down
            double res = 1;
            // here we calculate the total possible path number 
            // Combination(N, k) = n! / (k!(n - k)!)
            // reduce the numerator and denominator and get
            // C = ( (n - k + 1) * (n - k + 2) * ... * n ) / k!
            for (int i = 1; i <= k; i++)
                res = res * (N - k + i) / i;
            return (int)res;
        }
    };
posted @ 2017-09-12 23:30  清水汪汪  阅读(125)  评论(0编辑  收藏  举报