62. Unique Paths
Problem:
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?
给定一个m x n的网格,统计从(0,0)到(m-1,n-1)的不同路径,每次只能向右或向下走。
解决思路:从(0,0)到(i,j)的路径总数等于从(0,0)到(i-1,j)和从(0,0)到(i,j-1)路径数之和。
可以用动态规划,即dp[i][j]=dp[i-1][j]+dp[i][j-1]
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 vector<vector<int>> dp(m+1, vector<int>(n+1)); 5 dp[1][1] = 1; 6 for (int i=0; i<m; ++i) 7 for(int j=0; j<n; ++j) { 8 if (i==0 && j==0) 9 continue; 10 dp[i+1][j+1] = dp[i][j+1] + dp[i+1][j]; 11 } 12 13 return dp[m][n]; 14 } 15 };