Cover image for leetcode每日一题 P474 一和零

leetcode每日一题 P474 一和零


时间轴

时间轴

2025-11-11

init

0-1背包问题

题目:

属于经典的 0-1 背包问题,dp 要反向遍历以防重复使用。

1234567891011121314151617181920212223242526272829
#include <vector>#include <string>#include <algorithm>using std::vector;using std::string;class Solution {    public:	int findMaxForm(vector<string> &strs, int m, int n)	{		// 0-1背包问题		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;			// 关键:反向遍历,防止重复使用			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];	}};
评论加载中…