动态规划问题(三)-----矩阵最小路径和

 有一个矩阵map,它每个格子有一个权值。从左上角的格子开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,返回所有的路径中最小的路径和。

给定一个矩阵map及它的行数n和列数m,请返回最小路径和。保证行列数均小于等于100.

测试样例:

[[1,2,3],[1,1,1]],2,3
返回:4

(方法一)暴力搜索法

class MinimumPath {
public:
    int getMin(vector > map, int n, int m) {
        // write code here
        return foo(map,n-1,m-1);
    }
    int foo(vector >& map, int n, int m)
    {
        if(m==0&&n==0) return map[0][0];
        if(m==0) return map[m][n]+foo(map,n-1,m);
        if(n==0) return map[m][n]+foo(map,n,m-1);
        return map[m][n]+min(foo(map,n-1,m),foo(map,n,m-1));
    }
};

(方法二)记忆化搜索法

class MinimumPath {
public:
    int getMin(vector > map, int n, int m) {
        // write code here
        int dp[105][105];
        memset(dp,0,sizeof(dp));
        return foo(map,n-1,m-1,dp);
    }
    int foo(vector >& map, int n, int m,int (*dp)[105])
    {
        if(dp[n][m]) return dp[n][m];
        else if(m==0&&n==0) return dp[0][0]=map[0][0];
        else if(m==0) return dp[n][m]=map[n][m]+foo(map,n-1,m,dp);
        else if(n==0) return dp[n][m]=map[n][m]+foo(map,n,m-1,dp);
        return dp[n][m]=map[n][m]+min(foo(map,n-1,m,dp),foo(map,n,m-1,dp));
    }
};

(方法三)动态规划法

class MinimumPath {
public:
    int getMin(vector > map, int n, int m) {
        // write code here
        int dp[100][100];
        dp[0][0]=map[0][0];
        for(int i=1;i

 

你可能感兴趣的:(算法(动态规划))