我不了解如何将动态编程精确地用于最小路径求和问题。问题陈述如下。
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.
这是我尝试使用递归的代码。
#include "stdafx.h"
#include "vector"
#include "iostream"
#include "cmath"
#include "algorithm"
using namespace std;
class Solution {
public:
int s = INT_MAX;
int helper(int sum, vector<vector<int>> &grid, int i, int j) {
if (i == grid.size() - 1 && j == grid[0].size() - 1) {
return s = min(s, sum + grid[i][j]);
}
if (i >= grid.size() || j >= grid[0].size()) {
return sum;
}
return min(helper(sum + grid[i][j], grid, i + 1, j) + helper(sum + grid[i][j], grid, i, j + 1), s);
}
int minPathSum(vector<vector<int>>& grid) {
return helper(0, grid, 0, 0);
}
};
int main()
{
vector<int> v = { 1,2,3 };
vector<vector<int>> r;
r.push_back(v);
v = { 4,5,6 };
r.push_back(v);
v = { 7,8,9 };
r.push_back(v);
v = { 1,2,3 };
r.push_back(v);
Solution s;
cout<<s.minPathSum(r);
return 0;
}
以下是我尝试使用动态编程的代码,其中我将最小总和存储在给定索引[i,j]
并返回它,但它没有多大帮助,在线编码判断说“时间限制超标”
你能帮我改进代码吗?
#include "stdafx.h"
#include "vector"
#include "iostream"
#include "cmath"
#include "algorithm"
using namespace std;
class Solution {
public:
int s = INT_MAX;
int helper(int sum, vector<vector<int>> &grid, int i, int j,vector<vector<int>> &memoize) {
if (i == grid.size() - 1 && j == grid[0].size() - 1) {
return s = min(s, sum + grid[i][j]);
}
if (i >= grid.size() || j >= grid[0].size()) {
return sum;
}
if (sum + grid[i][j] < memoize[i][j])
memoize[i][j] = sum + grid[i][j];
else
return memoize[i][j];
return min(helper(sum + grid[i][j], grid, i + 1, j,memoize) + helper(sum + grid[i][j], grid, i, j + 1,memoize), s);
}
int minPathSum(vector<vector<int>>& grid) {
vector<vector<int>> memoize(grid.size(), vector<int>(grid[0].size(), INT_MAX));
return helper(0, grid, 0, 0,memoize);
}
};
int main()
{
vector<int> v = { 1,2,3 };
vector<vector<int>> r;
r.push_back(v);
v = { 4,5,6 };
r.push_back(v);
v = { 7,8,9 };
r.push_back(v);
v = { 1,2,3 };
r.push_back(v);
Solution s;
cout<<s.minPathSum(r);
return 0;
}