Leetcode 474. Ones and Zeroes

来源:互联网 发布:php bin2hex写入文件 编辑:程序博客网 时间:2024/06/07 10:51

题目:

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];    }};


原创粉丝点击