LeetCode OJ-62. Unique Paths(DP)

LeetCode OJ-62. Unique Paths(DP)

题目描述

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?

img

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

Note: m and n will be at most 100.

Subscribe to see which companies asked this question

题目理解

​ 在一个m*n的方格矩形中,要从(0, 0)移动到(m - 1, n - 1),求不同的路径总共有多少种。

​ dfs可以寻路,但去重很麻烦。这里要明确,无障碍物,每一个格子都能走到,且仅能往右和往下走。所以,我们可以确定,如果一个格子左边没有格子,或者上边没有格子,那到达该格子的路径就只会有1条。

​ 这里使用动态规划会比较容易处理,定义状态dp[i][j]为到达(i, j)时,有多少条不同的路径,对于没有左边格子或没有上边格子的位置,dp值就为1,而其他格子就依赖于到达其左边格子的不同路径数与其上边格子的不同路径数之和,状态转移方程可写作dp[i][j] = { 1, i = 0 || j = 0 } | { dp[i][j - 1] + dp[i - 1][j], i > 0 && j > 0 }。由此可得代码:

Code

const int g_kMaxSize = 101;
int g_res[g_kMaxSize][g_kMaxSize] = { 0 };

void dp(int m, int n)
{
    int i, j;
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
            if (i == 0 || j == 0) {
                g_res[i][j] = 1;
            }
            else {
                g_res[i][j] = g_res[i - 1][j] + g_res[i][j - 1];
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值