最小成本路径
给定成本矩阵cost[],cost[]中的位置(m,n),返回从 (0, 0) 到达 (m, n) 的最小成本路径的成本。
-
最优子结构
到达(m,n)必须通过(m-1,n),(m-1,n-1),(m,n-1)之一。minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n] -
重叠子结构
#include<bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
int min(int x,int y,int z);
int minCost(int cost[R][C],int m,int n){
if(n<0||m<0){
return INT_MAX;
}else if(m==0&&n==0){
return cost[m][n];
}else{
return cost[m][n]+min(minCost(cost,m-1,n-1),
minCost(cost,m-1,n),
minCost(cost,m,n-1));
}
}
int min(int x,int y,int z){
if(x<y){
return (x<z)?x:z;
}else{
return (y<z)?y:z;
}
}
int main(){
int cost[R][C]={ { 1, 2, 3 },
{ 4, 8, 2 },
{ 1, 5, 3 } };
cout<<minCost(cost,2,2)<<endl;
return 0;
}