三維dp+五重循環,我只想感嘆瘋狂套娃。
思路
定義
dp[i][j1][j2]:表示在i層,左側機器人在j1處,右側機器人在j2處。
初始化
dp[0][0][cols-1] = grid[0][0] + grid[0][cols-1];
遞推公式(j1!=j2時)
dp[i][j1][j2]=max(dp[i][j1][j2],dp[i-1][index1][index2]+grid[i][j1]+grid[i][j2]);
兩個注意點
1.j1
和j2
能達到的範圍和row有關係。
2.if(j1==j2)
本輪只能加一個值
代碼
class Solution {
public:
int cherryPickup(vector<vector<int>>& grid) {
int rows=grid.size();
int cols=grid[0].size();
int move[3]={-1,0,1};
int res=0;
vector<vector<vector<int>>> dp(rows,vector<vector<int>>(cols,vector<int>(cols,0)));
dp[0][0][cols-1] = grid[0][0] + grid[0][cols-1];
for(int i=1;i<rows;i++)
{
for(int j1=0;j1<min(i+1,cols);j1++)
{
for(int j2=cols-1;j2>=max(cols-i-1,0);j2--)
{
for(int k1=0;k1<3;k1++)
{
for(int k2=0;k2<3;k2++)
{
int index1=j1+move[k1];
int index2=j2+move[k2];
//越界
if(index1<0||index1>=cols||index2<0||index2>=cols)
continue;
if(j1!=j2)
dp[i][j1][j2]=max(dp[i][j1][j2],dp[i-1][index1][index2]+grid[i][j1]+grid[i][j2]);
else
dp[i][j1][j2]=max(dp[i][j1][j2],dp[i-1][index1][index2]+grid[i][j1]);
}
}
}
}
}
for(int j1=0;j1<cols;j1++)
{
for(int j2=cols-1;j2>=0;j2--)
res=max(res,dp[rows-1][j1][j2]);
}
return res;
}
};