Reputation: 321
I am trying to solve a dynamic programming question with recursive calls. dp[i][j]
should be equal to minimum ofdp[i-1][j], dp[i-1][j-1], dp[i-1][j+1]
. But i can only use the c++ minimum function for 2 variables, or a vector. I don't wanna push my results to a vector, so I am asking whats the best way I can solve this problem. Here is the code
int dpF(vector<vector<int>>& A, vector<vector<int>>dp,int i,int j)
{
if(i<0||i>=A.size()||j<0||j>A.size())
return 0;
if(dp[i][j]!=-1)
{
return dp[i][j];
}
dp[i][j]=A[i][j]+Math.min(dpF(A,dp,i-1,j-1),dpF(A,dp,i-1,j),dpF(A,dp,i-1,j+1)); //Here is the problem, I am trying to find an elegant way to return the minimum of these 3 values.
return dp[i][j];
}
Upvotes: 0
Views: 152
Reputation: 31
you can do min(dpF(A,dp,i-1,j-1),min(dpF(A,dp,i-1,j),dpF(A,dp,i-1,j+1));
Upvotes: 0
Reputation: 93274
std::min
provides an overload that accepts a std::initializer_list
. You can do:
std::min({dpF(A,dp,i-1,j-1), dpF(A,dp,i-1,j), dpF(A,dp,i-1,j+1)})
Upvotes: 4