1.问题描述
给定m行n列的网咯,每个格子(i,j)里都一个非负数A[i][j]
求一个从左上角(0,0)到右下角的路径,每一部只能向下或者向右走一步
使得路径上的格子里的数字之和最小
输出最小数字和
例如:
{
{1, 5, 7, 6, 8}
{4, 7, 4, 4, 9}
{10, 3, 2, 3, 2}
}
最小长度22
2.二维数组方法和滚动数组方法
//
// Created by Administrator on 2021/7/25.
//
#ifndef C__TEST01_MINPATHSUM_HPP
#define C__TEST01_MINPATHSUM_HPP
#include <vector>
class MinPathSum {
/*
* 给定m行n列的网咯,每个格子(i,j)里都一个非负数A[i][j]
* 求一个从左上角(0,0)到右下角的路径,每一部只能向下或者向右走一步
* 使得路径上的格子里的数字之和最小
* 输出最小数字和
* 例如:
* {
* {1, 5, 7, 6, 8}
* {4, 7, 4, 4, 9}
* {10, 3, 2, 3, 2}
* }
* 最小长度22
* */
public:
MinPathSum(vector<vector<int>> An);
int MinPathSumDP(vector<vector<int>> A);
int MinPathSumByScrollingArray(vector<vector<int>> A);
private:
vector<vector<int>> A;
};
MinPathSum::MinPathSum(vector<vector<int>> An):
A(An){
A.resize(An.size());
for (int i = 0; i < An.size(); ++i) {
A[i].resize(An.size());
}
}
int MinPathSum::MinPathSumDP(vector<vector<int>> A) {
if(A.size() == 0){
return 0;
}
vector<vector<int>> f;
f.resize(A.size());
for (int i = 0; i < A.size(); ++i) {
f[i].resize(A.size());
}
f[0][0] = A[0][0]; //Init
for (int i = 1; i < A.size(); ++i) {
f[i][0] = f[i-1][0] + A[i][0];
}
for (int j = 1; j < A[0].size(); ++j) {
f[0][j] = f[0][j-1] + A[0][j];
}
for (int i = 1; i < A.size(); ++i) {
for (int j = 1; j < A[i].size(); ++j) {
//f[i][j] = min{f[i][j-1]+A[i][j], f[i-1][j]+A[i][j]}
f[i][j] = INT_MAX;
f[i][j] = min(f[i][j-1]+A[i][j], f[i-1][j]+A[i][j]);
}
}
return f[A.size()-1][A[0].size()-1];
}
//scrolling array
int MinPathSum::MinPathSumByScrollingArray(vector <vector<int>> A) {
if(A.size() == 0){
return 0;
}
vector<vector<int>> f;
f.resize(2);
for (int i = 0; i < f.size(); ++i) {
f[i].resize(A[i].size());
}
//Initialization
f[0][0] = A[0][0];
int oldIndex = 0;
int newIndex = 0;
for (int j = 1; j < A[0].size(); ++j) {
f[0][j] = f[0][j-1] + A[0][j];
}
for(int i = 1; i < A.size(); ++i){
oldIndex = newIndex;
newIndex = 1 - oldIndex;
for(int j = 0; j < A[0].size(); ++j){
if(j == 0) f[newIndex][j] = f[oldIndex][j]+A[i][j];
else{
f[newIndex][j] = min(f[oldIndex][j]+A[i][j],
f[newIndex][j - 1]+A[i][j]);
}
}
}
return f[newIndex][f[newIndex].size()-1];
}
#endif //C__TEST01_MINPATHSUM_HPP
main.cpp
#include <iostream>
using namespace std;
#include "MinPathSum.hpp"
int main() {
vector<vector<int>> A = {
{1, 5, 7, 6, 8},
{4, 7, 4, 4, 9},
{10, 3, 2, 3, 2}
};
MinPathSum mps(A);
//cout<<mps.MinPathSumDP(A)<<endl;
cout<<mps.MinPathSumByScrollingArray(A)<<endl;
return 0;
}