Leetcode-474

Ones and Zeroes

Time complexity: $O(mn|strs|)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
#include <cstring>

class Solution {
public:
    int findMaxForm(std::vector<std::string>& strs, int m, int n) {
        std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1));
        for (std::string& str : strs) {
            int a = 0, b = 0;
            for (char c : str) {
                if (c == '0') {
                    ++a;
                }
                else {
                    ++b;
                }
            }
            for (int i = m; i >= a; --i) {
                for (int j = n; j >= b; --j) {
                    dp[i][j] = std::max(dp[i][j], 1 + dp[i - a][j - b]);
                }
            }
        }
        return dp.back().back();
    }
};

Leetcode-474

Licensed under CC BY-NC-SA 4.0