Timeline
Timeline
2025-11-11
init
0-1 knapsack problem
Problem:
It is a classic 0-1 knapsack problem; the dp array should be traversed in reverse to prevent reuse.
1234567891011121314151617181920212223242526272829 | using std::vector;using std::string;class Solution { public: int findMaxForm(vector<string> &strs, int m, int n) { // 0-1 knapsack problem int i, j; vector<vector<int> > dp(m + 1, vector<int>(n + 1, 0)); int zero_count, one_count; for (auto &s : strs) { zero_count = std::count(s.begin(), s.end(), '0'); one_count = s.size() - zero_count; // Key: traverse in reverse to prevent reuse for (i = m; i >= zero_count; --i) { for (j = n; j >= one_count; --j) { dp[i][j] = std::max(dp[i][j], dp[i - zero_count][j - one_count] + 1); } } } return dp[m][n]; }}; |
