首页 > 学院 > 开发设计 > 正文

62. Unique Paths 和63. Unique Paths II

2019-11-08 03:10:43
字体:
来源:转载
供稿:网友

一、62. Unique Paths 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? Note: m and n will be at most 100. 方法一、数学方法:

int uniquePaths(int m, int n) { int N = m + n -2; int k = m - 1; double res = 1; for(int i = 1; i <= k; i++) res = res * (N - k + i) / i; return (int)res; }

方法二、动态规划的方法:

int uniquePaths(int m, int n) { vector<vector<int>> path(m,vector<int> (n,1)); for(int i = 1; i < m; i++){ for(int j = 1; j < n; j++) path[i][j] = path[i-1][j] + path[i][j-1]; } return path[m - 1][n - 1]; }

二、63. Unique Paths II Follow up for “Unique Paths”: Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [ [0,0,0], [0,1,0], [0,0,0] ] The total number of unique paths is 2. Note: m and n will be at most 100. 动态规划:

int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<int>> dp(m+1,vector<int>(n+1,0)); dp[0][1] = 1; for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++) if(!obstacleGrid[i-1][j-1]) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } return dp[m][n]; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表