前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode474. Ones and Zeroes

leetcode474. Ones and Zeroes

作者头像
眯眯眼的猫头鹰
发布2019-10-08 18:46:46
3150
发布2019-10-08 18:46:46
举报

题目要求

代码语言:javascript
复制
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:

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

Example 1:

Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4

Explanation: 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 = 1
Output: 2

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

已知有m个0和n个1,问最多能构成数组中多少个数字。已知每个0和1只能使用一次。

思路和代码

先是用深度优先遍历的思想进行了实现,结果很明显是超时了。接着采用动态规划的思想,其实这题就是背包问题的一个演化。假设已知道m个0和n个1能够从数组中前i个元素最多拼成多少个元素,则m个0和n个1能够从数组中前i+1个元素能够拼成最多的元素个数有如下两个场景:

  1. 第i+1个字符串的0的个数和1的个数分别小于m和n,则有两种选择,分别是选择该字符串和不选择该字符串,选择该字符串的话,maxi+1[n] = 1 + maxi[n-numOfOne(str)], 如果不选择的话,maxi+1[n] = maxi-1[n]。从两个选项中选择一个最大的即可。
  2. 否则的话,maxi+1[n] = maxi[n]

代码如下:

代码语言:javascript
复制
    public int findMaxForm2(String[] strs, int m, int n) {
        int[][] dp = new int[m+1][n+1];
        for (String s : strs) {
            int[] count = count(s);
            for (int i=m;i>=count[0];i--) 
                for (int j=n;j>=count[1];j--) 
                    dp[i][j] = Math.max(1 + dp[i-count[0]][j-count[1]], dp[i][j]);
        }
        return dp[m][n];
    }
        
    public int[] count(String str) {
        int[] res = new int[2];
        for (int i=0;i<str.length();i++)
            res[str.charAt(i) - '0']++;
        return res;
     }
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com