classSolution { public: intfindMaxForm(vector<string>& strs, int m, int n){ int len = strs.size(); vector<vector<int>> cnt(len, vector<int>(2, 0)); for (int i = 0; i < len; i ++) { int zero = 0, one = 0; for (auto &c: strs[i]) { if (c == '1') one ++; else zero ++; } cnt[i][0] = zero, cnt[i][1] = one; }
vector<vector<int>> f(m + 1, vector<int>(n + 1, 0)); for (int k = 0; k < len; k ++) { int zero = cnt[k][0], one = cnt[k][1]; for (int i = m; i >= zero; i --) for (int j = n; j >= one; j --) { f[i][j] = max(f[i][j], f[i - zero][j - one] + 1); } } return f[m][n]; } };
classSolution { public: constint MOD = 1e9 + 7; // dp[i][j][k] 表示 前i个个物品,人数不超过j,利润至少为k的方案数 intprofitableSchemes(int n, int minProfit, vector<int>& group, vector<int>& profit){ int m = group.size(); vector<vector<int>> dp(n + 1, vector<int>(minProfit + 1, 0)); for (int i = 0; i <= n; i ++) dp[i][0] = 1; for (int i = 1; i <= m; i ++) { int a = group[i - 1], b = profit[i - 1]; for (int j = n; j >= a; j --) for (int k = minProfit; k >= 0; k --) { dp[j][k] += dp[j - a][max(k - b, 0)]; dp[j][k] %= MOD; } } return dp[n][minProfit]; } };
// d[i][j]代表考虑前 i 个物品(数值),凑成总和不超过 j 的最大价值。 classSolution { public: intlastStoneWeightII(vector<int>& stones){ int sum = 0, n = stones.size(); for (auto x: stones) sum += x; int t = sum / 2; vector<vector<int>> dp(n + 1, vector<int>(t + 1, 0)); for (int i = 1; i <= n; i ++) { int x = stones[i - 1]; for (int j = 0; j <= t; j ++) { dp[i][j] = dp[i - 1][j]; if (j >= x) dp[i][j] = max(dp[i][j], dp[i - 1][j - x] + x); } } return sum - 2 * dp[n][t]; } };
优化空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intlastStoneWeightII(vector<int>& stones){ int sum = 0, n = stones.size(); for (auto x: stones) sum += x; int t = sum / 2; vector<int> dp(t + 1, 0); for (int i = 1; i <= n; i ++) { int x = stones[i - 1]; for (int j = t; j >= x; j --) { dp[j] = max(dp[j], dp[j - x] + x); } } return sum - 2 * dp[t]; } };
classSolution { public: // dp[i][j] 表示 考虑前i个物品,总成本为j的最大整数长度 string largestNumber(vector<int>& cost, int t){ int n = cost.size(); vector<int> dp(t + 1, INT_MIN); dp[0] = 0; for (int i = 1; i <= n; i ++) { int x = cost[i - 1]; for (int j = x; j <= t; j ++) { dp[j] = max(dp[j], dp[j - x] + 1); } }
if (dp[t] < 0) return"0"; string res = ""; for (int i = 9, j = t; i >= 1; i --) { int x = cost[i - 1]; while (j >= x && dp[j] == dp[j - x] + 1) { res += to_string(i); j -= x; } } return res; } };