[LeetCode]62. Unique Paths

来源:互联网 发布:ceo cfo cmo 知乎 编辑:程序博客网 时间:2024/06/03 21:33

[LeetCode]62. Unique Paths

题目描述

这里写图片描述

思路

动态规划
考虑状态,当起始点与终点在同一点或同一条直线时,路径只有一条
那么当不在直线时考虑他到达相同直线的路径条数,即 dp[i][j] = dp[i][j + 1] + dp[i + 1][j]
假设对一个 2 x 3 的表格
我们可以按照上述表达计算每个格子到达终点的路径数

dp 0 1 2 0 3 2 1 1 1 1 1

代码

#include <iostream>#include <vector>using namespace std;class Solution {public:    int uniquePath(int m, int n) {        if (m == 0 || n == 0)            return 0;        vector<vector<int>> dp(m, vector<int>(n));        for(int i = m - 1; i >= 0; --i)            for (int j = n - 1; j >= 0; --j) {                if (i == m - 1 || j == n - 1)                    dp[i][j] = 1;                else                    dp[i][j] = dp[i][j + 1] + dp[i + 1][j];            }        return dp[0][0];    }};int main() {    Solution s;    cout << s.uniquePath(1, 1) << endl;    system("pause");    return 0;}
0 0
原创粉丝点击