LeetCode 题解:474. Ones and Zeroes

n the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.

For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.

Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.

Example

Input: Array = {“10”, “0”, “1”}, m = 1, n = 1
Output: 2
Explanation: You could form “10”, but then you’d have nothing left. Better form “0” and “1”.

解题思路

这道题和动态规划中经典的0/1背包问题很像。背包问题规定了背包的容量,而这道题规定了数字0和1的总数量。背包问题中的经典公式f[v] = max{f[v], f[v-c[i]]+w[i]}在这个问题中一样通用。不过由于要同时处理数字0和数字1的数量,因此使用二维数组存储此结构。
算法如下:
1、对于一个新的字符串,首先先统计字符串中含有字符“1”和“0”的数量。
2、套用背包问题的经典公式,利用双重循环更新背包空间的状态数组
3、当遍历所有字符串后,将 dp[m][n]上保存的值输出。

C++代码

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
        int amount1 = 0, amount0 = 0;
        for(vector<string>::iterator str = strs.begin(); str != strs.end(); str++) {
            amount1 = 0;
            amount0 = 0;
            for(int i = 0; i < (*str).size(); i++) {
                if((*str)[i] == '1')
                    amount1++;
                else
                    amount0++;
            }
            for(int i = m; i >= amount0; i--) {
                for(int j = n; j >= amount1; j--) {
                    dp[i][j] = max(dp[i][j], dp[i-amount0][j-amount1]+1);
                }
            }
        }
        return dp[m][n];
    }
};

你可能感兴趣的:(LeetCode题解)