算法设计与应用基础:第十四周(2)

474. Ones and Zeroes

  • Total Accepted: 9440
  • Total Submissions: 24868
  • Difficulty: Medium
  • Contributors:piy9

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.
解题思路:也是背包问题的变式,只不过将重量转变为0和1的个数,状态转移方程为dp[p][j]=max(dp[p-helper[i-1][0]][j-helper[i-1][1]]+1,dp[p][j]);
代码为:
int findMaxForm(vector<string>& strs, int m, int n) {
    int size=strs.size();
    int helper[size][2];
    memset(helper,0,sizeof(helper));
    for(int i=0;i<strs.size();i++)
    {
        int t1=0,t0=0;
        for(int p=0;p<strs[i].size();p++)
        {
            if(strs[i][p]=='0')
                t0++;
            else
                t1++;
        }
        helper[i][0]=t0;
        helper[i][1]=t1;
    }
    int dp[m+1][n+1];
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=size;i++)
    {
        for(int p=m;p>=helper[i-1][0];p--)
        {
            
                for(int j=n;j>=helper[i-1][1];j--)
                {
                    
                        dp[p][j]=max(dp[p-helper[i-1][0]][j-helper[i-1][1]]+1,dp[p][j]);
                    //else
                       // dp[i][p][j]=max(dp[i-1][p][j],dp[i][p][j]);
                    //cout<<i<<" "<<p<<" "<<j<<" "<<dp[i][p][j]<<endl;
                    
                }
            
           }
    }
    return dp[m][n];

收获:空间复杂度的提高,不需要三维数组(在简单背包问题中对应于一维数组)只需要二维数组,注意一定要是简单背包问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值