diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index 47b34a0f..7b46abee 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -159,7 +159,89 @@ public: * 时间复杂度: O(kmn),k 为strs的长度 * 空间复杂度: O(mn) +C++: +使用三维数组的版本 +```CPP +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + int num_of_str = strs.size(); + + vector>> dp(num_of_str, vector>(m + 1,vector(n + 1, 0))); + + /* dp[i][j][k] represents, if choosing items among strs[0] to strs[i] to form a subset, + what is the maximum size of this subset such that there are no more than m 0's and n 1's in this subset. + Each entry of dp[i][j][k] is initialized with 0 + + transition formula: + using x[i] to indicates the number of 0's in strs[i] + using y[i] to indicates the number of 1's in strs[i] + + dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - x[i]][k - y[i]] + 1) + + */ + + + // num_of_zeros records the number of 0's for each str + // num_of_ones records the number of 1's for each str + // find the number of 0's and the number of 1's for each str in strs + vector num_of_zeros; + vector num_of_ones; + for (auto& str : strs){ + int count_of_zero = 0; + int count_of_one = 0; + for (char &c : str){ + if(c == '0') count_of_zero ++; + else count_of_one ++; + } + num_of_zeros.push_back(count_of_zero); + num_of_ones.push_back(count_of_one); + + } + + + // num_of_zeros[0] indicates the number of 0's for str[0] + // num_of_ones[0] indiates the number of 1's for str[1] + + // initialize the 1st plane of dp[i][j][k], i.e., dp[0][j][k] + // if num_of_zeros[0] > m or num_of_ones[0] > n, no need to further initialize dp[0][j][k], + // because they have been intialized to 0 previously + if(num_of_zeros[0] <= m && num_of_ones[0] <= n){ + // for j < num_of_zeros[0] or k < num_of_ones[0], dp[0][j][k] = 0 + for(int j = num_of_zeros[0]; j <= m; j++){ + for(int k = num_of_ones[0]; k <= n; k++){ + dp[0][j][k] = 1; + } + } + } + + /* if j - num_of_zeros[i] >= 0 and k - num_of_ones[i] >= 0: + dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - num_of_zeros[i]][k - num_of_ones[i]] + 1) + else: + dp[i][j][k] = dp[i-1][j][k] + */ + + for (int i = 1; i < num_of_str; i++){ + int count_of_zeros = num_of_zeros[i]; + int count_of_ones = num_of_ones[i]; + for (int j = 0; j <= m; j++){ + for (int k = 0; k <= n; k++){ + if( j < count_of_zeros || k < count_of_ones){ + dp[i][j][k] = dp[i-1][j][k]; + }else{ + dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - count_of_zeros][k - count_of_ones] + 1); + } + } + } + + } + + return dp[num_of_str-1][m][n]; + + } +}; +``` ## 总结