# leetcode #62 in cpp

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];
}
};

• 本文已收录于以下专栏：

## leetcode #86 in cpp

Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr...

## leetcode #24 in cpp

The question is to swap each pair in the linked list. And the requirement is to use constant space. ...

## Leetcode 450. Delete Node in a BST (Medium) (cpp)

Leetcode 450. Delete Node in a BST (Medium) (cpp)
• Niko_Ke
• 2016年12月26日 07:50
• 269

## leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

## leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

## Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)
• Niko_Ke
• 2016年12月28日 03:38
• 240

## leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

## leetcode #36 in cpp.

The question is to determine a Sudoku is valid.  Solution:  if a Sudoku is valid, each row, each co...

## *leetcode 138 in cpp

A linked list is given such that each node contains an additional random pointer which could point t...

## leetcode #17 in cpp

The question is : Given a digit string, return all possible letter combinations that the number coul...

举报原因： 您举报文章：leetcode #62 in cpp 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)