【题解】牛妹的礼物
牛妹的礼物
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
*/
查看25道真题和解析
三奇智元机器人科技有限公司公司福利 50人发布
