背包问题
有N个重量和价值分别为wi和vi的物品。
从这些物品中挑选出总重量不超过W的物品,求所有挑选方案中价值总和的最大值。
#define MAX_N 1000 // input int N, W, w[MAX_N], v[MAX_N]; int dp[MAX_N][MAX_N]; // remember array to reduce recursive int rec(int i, int weight) { if(dp[i][weight] >= 0) return dp[i][weight]; int ans; if(i == N) // no product left ans = 0; if(w[i] > weight) // can not include this product ans = rec(i+1, weight); else ans = max(rec(i+1, weight), rec(i+1, weight - w[i]) + v[i]); return dp[i][weight] = ans; } void solve() { printf("%d\n", rec(0, W)); }