[LeetCode] 474. Ones and Zeroes

题:https://leetcode.com/problems/ones-and-zeroes/description/

题目

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".

题目大意

有一组 字符串 string,给定 m个‘1’,与n个‘0’。选择字符串组,使用的‘1’与‘0’小于 m与n。
求最多有多少个 字符串。

思路

这是一个多维费用的 0-1 背包问题,有两个背包大小,0 的数量和 1 的数量。

状态 dp[i][j][k]:遍历到 第 i个 物品(字符串),使用 j个’0’ 、 k个’1’时,能包含的最多 物品数(字符串数)

状态转移方程:

 if(j-num0>=0 && k-num1>=0)
     dp[i][j][k] = Math.max(dp[i-1][j][k],dp[i-1][j-num0][k-num1]+1);
 else
     dp[i][j][k] = dp[i-1][j][k];

初始化
dp[0][j][k] = 0;

扫描二维码关注公众号,回复: 4012710 查看本文章
class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        int [][][]dp = new int[strs.length+1][m+1][n+1];
        for(int i = 1;i <= strs.length;i++){
            
            int num0 = 0;
            int num1 = 0;
            for(int j = 0 ;j<strs[i-1].length();j++){
                if(strs[i-1].charAt(j)=='0')
                    num0 ++;
                else
                    num1 ++;
            }
            
            for(int j = 0;j<=m;j++)
                for(int k = 0;k<=n;k++){
                    if(j-num0>=0 && k-num1>=0)
                        dp[i][j][k] = Math.max(dp[i-1][j][k],dp[i-1][j-num0][k-num1]+1);
                    else
                        dp[i][j][k] = dp[i-1][j][k];
                }
        }
        return dp[strs.length][m][n];
    }
}

由于 dp[i][j][k] 只用到了 dp[i-1],所以 可以用 二维数组表示 dp。

class Solution {
    public int findMaxForm(String[] strs, int m, int n) {
        int[][] dp = new int[m+1][n+1];
        for(String str:strs){
            int num0 = 0;
            int num1 = 0;
            for(int j = 0;j<str.length();j++){
                if(str.charAt(j)=='0')
                    num0++;
                else
                    num1++;
            }
            for(int j = m;j>=num0;j--)
                for(int k = n;k>=num1;k--)
                    dp[j][k] = Math.max(dp[j][k],dp[j-num0][k-num1]+1);
        }
        return dp[m][n];
    }
}

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/83749443