Title:
https://leetcode.com/problems/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.
思路:直观的思路是使用递归,但是会超时
class Solution{ public: int m; int n; int uniquePaths(int m, int n) { this->m = m; this->n = n; int sum = 0; fun(1,1,sum); return sum; } void fun(int i,int j,int& sum){ if (i == m && j == n) sum++; if (i > m || j > n) return ; fun(i+1,j,sum); fun(i,j+1,sum); } };
int uniquePaths(int m,int n){ if (m == 1 || n == 1) return 1; return uniquePaths(m-1,n)+uniquePaths(m,n-1); }
一般这种递归都可以使用动态规划来解决
class Solution{ public: int uniquePaths(int m,int n){ if (m < 1 || n < 1) return 0; vector<int> v(n,1); for (int i = 1; i < m ; i++) for (int j = 1; j < n;j++){ v[j] += v[j-1]; } return v[n-1]; } };
Unique Path II
https://leetcode.com/problems/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.
开始想直接使用I中的,却没有考虑到边界上有障碍的情况
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid){ if (obstacleGrid.empty()) return 0; int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); if (m < 1 || n < 1) return 0; vector<int> result(n); result[0] = 1; for (int i = 0 ; i < m ; i++){ for (int j = 0 ; j < n ; j++){ if (obstacleGrid[i][j] == 1) result[j] = 0; else{ if (j > 0) result[j] += result[j-1]; } } } return result[n-1]; }
Minimun-Path-Sum
Title:
https://leetcode.com/problems/minimum-path-sum/
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
思路:同样的动态规划
class Solution{ public: int minPathSum(vector<vector<int> > &grid){ if (grid.empty() || grid.size() == 0) return 0; int m = grid.size(); int n = grid[0].size(); vector<int> v(n,INT_MAX); v[0] = 0; for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++){ if (j == 0){ v[j] = v[j] + grid[i][j]; }else{ v[j] = min(v[j],v[j-1]) + grid[i][j]; } //cout<<v[j]<<" "; } //cout<<endl; } //cout<<endl; return v[n-1]; } };