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];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值