@@ -159,7 +159,89 @@ public:
159159* 时间复杂度: O(kmn),k 为strs的长度
160160* 空间复杂度: O(mn)
161161
162+ C++:
163+ 使用三维数组的版本
162164
165+ ```CPP
166+ class Solution {
167+ public:
168+ int findMaxForm(vector<string>& strs, int m, int n) {
169+ int num_of_str = strs.size();
170+
171+ vector<vector<vector<int>>> dp(num_of_str, vector<vector<int>>(m + 1,vector<int>(n + 1, 0)));
172+
173+ /* dp[i][j][k] represents, if choosing items among strs[0] to strs[i] to form a subset,
174+ 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.
175+ Each entry of dp[i][j][k] is initialized with 0
176+
177+ transition formula:
178+ using x[i] to indicates the number of 0's in strs[i]
179+ using y[i] to indicates the number of 1's in strs[i]
180+
181+ dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - x[i]][k - y[i]] + 1)
182+
183+ */
184+
185+
186+ // num_of_zeros records the number of 0's for each str
187+ // num_of_ones records the number of 1's for each str
188+ // find the number of 0's and the number of 1's for each str in strs
189+ vector<int> num_of_zeros;
190+ vector<int> num_of_ones;
191+ for (auto& str : strs){
192+ int count_of_zero = 0;
193+ int count_of_one = 0;
194+ for (char &c : str){
195+ if(c == '0') count_of_zero ++;
196+ else count_of_one ++;
197+ }
198+ num_of_zeros.push_back(count_of_zero);
199+ num_of_ones.push_back(count_of_one);
200+
201+ }
202+
203+
204+ // num_of_zeros[0] indicates the number of 0's for str[0]
205+ // num_of_ones[0] indiates the number of 1's for str[1]
206+
207+ // initialize the 1st plane of dp[i][j][k], i.e., dp[0][j][k]
208+ // if num_of_zeros[0] > m or num_of_ones[0] > n, no need to further initialize dp[0][j][k],
209+ // because they have been intialized to 0 previously
210+ if(num_of_zeros[0] <= m && num_of_ones[0] <= n){
211+ // for j < num_of_zeros[0] or k < num_of_ones[0], dp[0][j][k] = 0
212+ for(int j = num_of_zeros[0]; j <= m; j++){
213+ for(int k = num_of_ones[0]; k <= n; k++){
214+ dp[0][j][k] = 1;
215+ }
216+ }
217+ }
218+
219+ /* if j - num_of_zeros[i] >= 0 and k - num_of_ones[i] >= 0:
220+ dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - num_of_zeros[i]][k - num_of_ones[i]] + 1)
221+ else:
222+ dp[i][j][k] = dp[i-1][j][k]
223+ */
224+
225+ for (int i = 1; i < num_of_str; i++){
226+ int count_of_zeros = num_of_zeros[i];
227+ int count_of_ones = num_of_ones[i];
228+ for (int j = 0; j <= m; j++){
229+ for (int k = 0; k <= n; k++){
230+ if( j < count_of_zeros || k < count_of_ones){
231+ dp[i][j][k] = dp[i-1][j][k];
232+ }else{
233+ dp[i][j][k] = max(dp[i-1][j][k], dp[i-1][j - count_of_zeros][k - count_of_ones] + 1);
234+ }
235+ }
236+ }
237+
238+ }
239+
240+ return dp[num_of_str-1][m][n];
241+
242+ }
243+ };
244+ ```
163245
164246## 总结
165247
0 commit comments