码迷,mamicode.com
首页 > 其他好文 > 详细

474. Ones and Zeroes

时间:2017-02-28 20:56:02      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:can   most   for   res   one   max   动态规划   --   number   

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 only0s 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 mostonce.

代码如下:(动态规划)

解析:

状态转换公式:dp[i][j]=Math.max(dp[i-a[0]][j-a[1]+1],dp[i][j])

public class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        if(m==0&&n==0)
        return 0;                                                                                                                           
        if(m<0||n<0)
        return 0;
        int[][] dp=new int[m+1][n+1];
        
        for(int i=0;i<strs.length;i++)
        {
            String s=strs[i];
            int[] a=abs(s);
            for(int j=m;j>=a[0];j--)//备忘录的自顶向下
            {
                for(int k=n;k>=a[1];k--)
                {
                    dp[j][k]=Math.max(dp[j-a[0]][k-a[1]]+1,dp[j][k]);
                }
            }
        }
        return dp[m][n];
    }
    int[] abs(String s){   //用于统计每个字符串中0和1的个数
        int[] a=new int[2];
         for(int i=0;i<s.length();i++)
            {
                if(s.charAt(i)==‘0‘)
                a[0]++;
                else
                a[1]++;
            }
            return a;
    }
}

  

474. Ones and Zeroes

标签:can   most   for   res   one   max   动态规划   --   number   

原文地址:http://www.cnblogs.com/ghuosaao/p/6480677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!