標籤:leetcoed 動態規劃 最小路徑 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.
首先每一個路徑的上一個路徑都是來自於其上方和左方
現將最上面的路徑進行求和,最左邊的路徑進行求和(這裡沒有直接求和的原因是因為用一個一維數組res[n]記錄路徑,這裡比較巧妙得節約了空間,所以將最左邊的求和演算法放到了迴圈裡面 res[i][j] = min(res[i-1][j],res[i][j-1])+val[i][j] )
class Solution {public: int minPathSum(vector<vector<int> > &grid) { if(grid.empty() || grid[0].empty()) { return 0; } int m = grid.size(); int n = grid[0].size(); int *res = new int[n]; res[0] = grid[0][0]; for(int i = 1;i < n; i++) { res[i] = res[i-1]+grid[0][i]; } for(int i = 1; i < m; i++) { for(int j = 0; j < n; j++) { if (0 == j) { res[j] += grid[i][0]; } else { res[j] = min(res[j-1],res[j])+grid[i][j]; } } } int result = res[n-1]; delete []res; return result; }};
和這種動態規劃類似的演算法還有:
Unique Paths
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 uniquePaths(int m, int n) { if(m == 0 || n == 0) { return 0; } int res[100][100]; for(int i = 0; i < n; i++) { res[0][i] = 1; //<因為只有一種方法 } for(int i = 0; i < m; i++) { res[i][0] = 1; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { res[i][j] = res[i-1][j]+res[i][j-1]; } } return res[m-1][n-1]; }};
如果只是利用一維空間:
class Solution {public: int uniquePaths(int m, int n) { if(m <= 0 || n <= 0 { return 0; } int res[100] = {0}; res[0] = 1; for(int i = 0; i < m; i++) { for(int j = 1; j < n; j++) { res[j] += res[j-1]; } } return res[n-1]; }};
Unique Paths II
這裡涉及到一些障礙物的情況,如果值為1表示這裡有障礙物,不能跨越
[ [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.
class Solution {public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { if(obstacleGrid.empty() || obstacleGrid[0].empty()) { return 0; } int res[100] = {0};//<還是採用一維數組 int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); res[0] = (obstacleGrid[0][0] != 1); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { <span style="color:#ff0000;">if(j == 0) { if(obstacleGrid[i][j] == 1) //<這裡需要稍微注意一下如果當前有障礙表示為0,否則可以延續之前的狀態 { res[j] = 0; } }</span> else { <span style="color:#ff0000;">if(obstacleGrid[i][j] == 1) { res[j] = 0; } else { res[j] += res[j-1]; }</span> } } } return res[n-1]; }};
LeetCode—Minimum Path Sum 二維數組最小路徑,動態規劃