LeetCode【474. 一和零】

给你一个二进制字符串数组 strs 和两个整数 m 和 n 。

请你找出并返回 strs 的最大子集的长度,该子集中 最多 有 m 个 0 和 n 个 1 。

如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 。

示例 1:

输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
输出:4
解释:最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。
其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 。

示例 2:

输入:strs = ["10", "0", "1"], m = 1, n = 1
输出:2
解释:最大的子集是 {"0", "1"} ,所以答案是 2 。

提示:

  • 1 <= strs.length <= 600
  • 1 <= strs[i].length <= 100
  • strs[i] 仅由 '0' 和 '1' 组成
  • 1 <= m, n <= 100

答:咱们可以使用动态规划来解决这个问题。

public 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[] count = countZerosOnes(strs[i - 1]);
            int zeros = count[0];
            int ones = count[1];

            for (int j = 0; j <= m; j++) {
                for (int k = 0; k <= n; k++) {
                    if (j >= zeros && k >= ones) {
                        dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - zeros][k - ones] + 1);
                    } else {
                        dp[i][j][k] = dp[i - 1][j][k];
                    }
                }
            }
        }

        return dp[strs.length][m][n];
    }

    private int[] countZerosOnes(String str) {
        int[] count = new int[2];
        for (char c : str.toCharArray()) {
            if (c == '0') {
                count[0]++;
            } else if (c == '1') {
                count[1]++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] strs1 = {"10", "0001", "111001", "1", "0"};
        int m1 = 5, n1 = 3;
        System.out.println(solution.findMaxForm(strs1, m1, n1)); // 输出:4

        String[] strs2 = {"10", "0", "1"};
        int m2 = 1, n2 = 1;
        System.out.println(solution.findMaxForm(strs2, m2, n2)); // 输出:2
    }
}

首先创建一个二维数组 dp,其中 dp[i][j] 表示使用前 i 个字符串(strs[0] 到 strs[i-1])时,可以使用最多 j 个 '0' 和最多 k 个 '1' 的最大子集的长度。

然后,你可以按顺序遍历每个字符串,考虑将其包含在子集中或不包含在子集中的情况,然后更新 dp 数组。最后,dp[strs.length][m][n] 即为所求的答案,

我们利用 三维动态规划数组 dp,时间复杂度为 O(strs.length * m * n)。

猜你喜欢

转载自blog.csdn.net/s_sos0/article/details/133325706