这种的动态规划题目主要还是不能被自己的思路限制了,之前的dp[i][j]是“最大值”;
这里得把dp[i][j]理解为前i个物品放到j容的背包中的方法;
那么很显然有递推公式:
代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef long long ll;
using namespace std;
const int N = 1e4 + 5;
ll n, m;
ll val[N];
ll dp[N][N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
for (int i = 1; i <= n; i++)cin >> val[i];
for (int i = 1; i <= n; i++)
{
for (int j = 0; j <= m; j++)
{
if (val[i] > j)dp[i][j] = dp[i - 1][j];
else if (val[i] == j)dp[i][j] = dp[i - 1][j] + 1;
else dp[i][j] = dp[i - 1][j] + dp[i - 1][j - val[i]];
}
}
cout << dp[n][m];
return 0;
}
srds我不明白我的dfs为什么会T啊!QAQ
贴,以后看:
ll dfs(ll i, ll j)
{
// 前i个物品装到容量为j的包中的种数
if (dp[i][j] != 0)return dp[i][j];
if (i == 0)return 0;
ll res = 0;
if (val[i] > j)res = dfs(i - 1,j);
else if (val[i] == j)res = dfs(i - 1, j) + 1;
else res = dfs(i - 1, j) + dfs(i - 1, j - val[i]);
return dp[i][j] = res;
}
标签:val,res,ll,dfs,P1164,点菜,include,dp
From: https://www.cnblogs.com/zzzsacmblog/p/18113953