【题解】牛妹的礼物

牛妹的礼物

http://www.nowcoder.com/questionTerminal/c4f777778e3040358e1e708750bb7fb9

表示到达第 行 第 列的最小和。
第一行和第一列单独考虑:

  • 对于第一行的位置,肯定是从转移过来的。
  • 对于第一列的位置,肯定是从转移过来的。
  • 对于其他位置 来说,可能是从上边,左边,左上方过来的,所以有了状态转移方程
#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    /*
     *
     * @param presentVolumn int整型vector<vector<>> N*M的矩阵,每个元素是这个地板砖上的礼物体积
     * @return int整型
     */
    int selectPresent(vector<vector<int> >& presentVolumn) {
        // write code here
        int N = presentVolumn.size();
        int M = presentVolumn[0].size();
        int dp[310][310];
        dp[0][0]=presentVolumn[0][0];
        for(int j = 1 ; j < M ; j++)
        {
            dp[0][j] = dp[0][j-1]+presentVolumn[0][j];
        }
        for(int i = 1 ; i < N; i++)
        {
            dp[i][0] = dp[i-1][0]+presentVolumn[i][0];
        }
        for(int i = 1 ; i < N ; i++)
        {
            for(int j = 1 ; j < M ; j++)
            {
                dp[i][j] = min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+presentVolumn[i][j];
            }
        }
        return dp[N-1][M-1];
    }
};

int main()
{
    int N,M;
    cin>> N >> M;
    vector<vector<int> > presentVolumn(N);
    int t = 0;
    for(int i = 0 ; i < N ; i++)
    {
        for(int j = 0 ; j < M ; j++)
        {
            cin >> t;
            presentVolumn[i].push_back(t);
        }
    }
    Solution S;
    cout<<S.selectPresent(presentVolumn);
    //selectPresent(presentVolumn);
    return 0;
}
/*
2 3
1 2 3
2 3 4
*/
全部评论
清楚姐姐yyds
点赞 回复 分享
发布于 2020-08-18 15:48
点赞 回复 分享
发布于 2020-08-18 15:42

相关推荐

不愿透露姓名的神秘牛友
06-13 19:30
化身华黑&nbsp;今天询问对接人审批情况,结果被告知没HC了&nbsp;云计算&nbsp;
苦闷的柠檬精allin实习:主管面结束后hr每周保温一次,结果前几天和我说没hc了,我也化身华黑子了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务