62. Unique Paths

Description:

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?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


簡要題解:

採用動態規劃。將grid抽象爲有向圖,每一個格子爲圖中的一個結點,圖中包含所有向下和向右的邊。令C(i, j)爲以grid[0][0]爲起點,grid[i][j]爲終點的路徑個數(i或j小於0時,C(i, j) = 0)。則C(0, 0) = 1,並且,一般地,C(i, j) = C(i - 1, j) + C(i, j - 1),便可求出從起點到終點的路徑個數。


代碼:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int> > grid;

        grid.resize(m);
        for (int i = 0; i < m; i++)
            grid[i].resize(n);

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                grid[i][j] = 0;

        grid[0][0] = 1;

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (i > 0)
                    grid[i][j] += grid[i-1][j];
                if (j > 0)
                    grid[i][j] += grid[i][j-1];
            }
        
        return grid[m-1][n-1];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章