关闭

leetcode #62 in cpp

标签: cppleetcode
42人阅读 评论(0) 收藏 举报

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?


Solution:

Suppose if w are currently in  a cell, we can only move right or down. Thus the number of paths from this cell to the destination is the sum the number of paths to destination from the cell right next to it,  and the number of paths to the destination from the cell blow it . 

We use DP to solve this. 

dp[i][j] = number of paths of the position(i+1, j + 1) to the destination

  = dp[i+1][j] + d[[i][j+1]

The initialization involves the bottom row and rightmost column, both initialized to 1 since they can move in only 1 direction.


Code:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> dp(m, vector<int>(n,0));//dp[i][j] = number of paths to destination
        dp[m-1][n-1] = 1;//destination to 1
        for(int i = 0; i < m && n-1 >=0; i ++){// right border to 1 
            dp[i][n-1] = 1;
        }
        for(int i = 0; i < n && m-1 >= 0; i ++){//bottom border to 1
            dp[m-1][i] = 1;
        }
        for(int i = m-2; i >=0; i --){
            for(int j = n-2; j>=0; j --){
                dp[i][j]+= dp[i][j+1] + dp[i+1][j];//current path number = num of its righr cell paths + num of its down cell paths to destination
            }
        }
        return dp[0][0];
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7949次
    • 积分:1395
    • 等级:
    • 排名:千里之外
    • 原创:139篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档