474. Ones and Zeroes

来源:互联网 发布:傅园慧表情包刷爆网络 编辑:程序博客网 时间:2024/05/20 11:24

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.

Note:

  1. The given numbers of 0s and 1s will both not exceed 100
  2. The size of given string array won't exceed 600.

Example 1:

Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3Output: 4Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”

Example 2:

Input: Array = {"10", "0", "1"}, m = 1, n = 1Output: 2

Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".

使用dp[i][j]表示当有i个0,j个1时,能得到的最多的字符串个数,遍历输入的数组,讨论每一个字符串是否考虑在内,递推公式:

dp[i][j]=max(dp[i][j],dp[i-zeros][j-ones]+1)

其中,zeros是当前字符串零的个数,ones是1的个数,如果将当前字符串包含在内,则dp[i][j]=dp[i-zeros][j-ones]+1;如果不讲当前字符考虑在内,总数不变。

class Solution {public:    int findMaxForm(vector<string>& strs, int m, int n) {        int nums=strs.size();        vector<vector<int>> res(m+1,vector<int>(n+1,0));        for(int i=0;i<nums;i++)        {            int zeros=0,ones=0;            for(int j=0;j<strs[i].size();j++)            {                if(strs[i][j]=='0') zeros++;                else if(strs[i][j]=='1') ones++;                            }            for(int k=m;k>=zeros;k--)            for(int l=n;l>=ones;l--)            res[k][l]=max(res[k-zeros][l-ones]+1,res[k][l]);        }        return res[m][n];    }};


0 0
原创粉丝点击