Unique Paths

来源:互联网 发布:js 数组 clear 编辑:程序博客网 时间:2024/06/04 18:18

A robot is located at the top-leftcorner of a m x n grid (marked 'Start' in thediagram below).

The robot can onlymove either down or right at any point in time. The robot is trying to reachthe bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possibleunique paths are there?

Note: m and n will be at most 100.

思路:典型动态规划法思路,关键是定义清楚状态dp[i][j]到底表示什么。这题中,因为要求到底多少unique path的个数,所以dp[i][j]可以定义为到[i,j]位置的时候有多少种走法。又因为题目限制了只能右移或者下移,所以每个dp[i][j]只能从dp[i-1][j]dp[i][j-1]过来,这样就得出递推公式,dp[i][j]=dp[i-1][j] + dp[i][j-1]

class Solution {public:    int uniquePaths(int m, int n) {        if (m == 0 || n == 0) {            return 0;        }                if (m == 1 || n == 1) {            return 1;        }                //dp[i][j]表示到当前的走法的种数        vector< vector<int> > dp(m, vector<int>(n, 0));                // 只有一行时,到每个格子的走法只有一种        for (int i = 0; i < m; i++) {            dp[i][0] = 1;        }                //只有一列时,到每个格子的走法也只有一种        for (int j = 0; j < n; j++) {            dp[0][j] = 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];    }};


0 0
原创粉丝点击