474 Ones and Zeroes

In the computing world, we always seek to maximize the benefits with limited resources.
Now, suppose you dominate m 0s and n 1s, respectively. Also, there is an array containing only 0 and 1 strings.
Your task is to find the maximum number of strings that can be spelled out in the array, given m zeros and n ones. Each 0 and 1 is used at most once.
Note:
    The number of given 0s and 1s will not exceed 100.
    The length of the given string array will not exceed 600.
Example 1:
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: A total of 4 strings can be passed through 5 0 and 3 1s spelled out, i.e. "10","0001","1","0" .

Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You can spell "10", but after that there are no remaining digits. A better option is to spell out "0" and "1".
See: https://leetcode.com/problems/ones-and-zeroes/description/

C++:

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n)
    {
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
        for (string str : strs) 
        {
            int zeros = 0, ones = 0;
            for (char c : str) 
            {
                (c == '0') ? ++zeros : ++ones;
            }
            for (int i = m; i >= zeros; --i)
            {
                for (int j = n; j >= ones; --j)
                {
                    dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
                }
            }
        }
        return dp[m][n];
    }
};

 参考:https://www.cnblogs.com/grandyang/p/6188893.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599196&siteId=291194637