Leetcode 474. Ones and Zeroes

题目:

In 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.

思路:dp算法求解,如果假设dp[i][j]为i个0和j个1组成的组合数,那当有n个字符串的时候相应的d[i][j]就肯定为n,如果再加入一个字符串相应的dp[i+s][j+t]=dp[i][s]+1,也就是n+1(字符串的总数)可得状态方程。

class Solution {
public:
    vector<int> countn(string s) {
        vector<int> re(2,0);
        for(int i=0;i<s.size();i++) {
            re[s[i]-'0']++;
        }
        return re;
    }
    int findMaxForm(vector<string>& strs, int m, int n) {
        int dp[m+1][n+1]={};
        int len=strs.size();
        for (auto s : strs) {
            vector<int> count = countn(s);
            for (int i=m;i>=count[0];i--) 
                for (int j=n;j>=count[1];j--)
                    dp[i][j] = max(1 + dp[i-count[0]][j-count[1]], dp[i][j]);
        }
        return dp[m][n];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值