其他分享
首页 > 其他分享> > 【LeetCode-494】一和零

【LeetCode-494】一和零

作者:互联网

问题

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

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

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

示例

输入: 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 。

解答

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        int dp[m + 1][n + 1]; memset(dp, 0, sizeof dp);
        for (string s : strs) {
            int cnt0 = 0, cnt1 = 0;
            for (char ch : s) { // 计算当前元素的0和1数量
                if (ch == '0') cnt0++;
                else cnt1++;
            }
            for (int i = m; i >= cnt0; i--)
                for (int j = n; j >= cnt1; j--)
                    dp[i][j] = max(dp[i][j], dp[i - cnt0][j - cnt1] + 1);
        }
        return dp[m][n];
    }
};

重点思路

本题需要关心一个物品的两个属性,但每个物品只能取一次,所以还是01背包问题。对于每一个元素,我们只需要计算其包含的0和1的数量,由于是“不超过mn”,所以不需要加额外的判断,直接取最大值即可。

拓展

如果题目要求的是“该子集中有m个0和n个1”,该如何求解。

解答

class Solution {
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        int dp[m + 1][n + 1]; memset(dp, -1, sizeof dp);
        dp[0][0] = 0;
        for (string s : strs) {
            int cnt0 = 0, cnt1 = 0;
            for (char ch : s) {
                if (ch == '0') cnt0++;
                else cnt1++;
            }
            for (int i = m; i >= cnt0; i--)
                for (int j = n; j >= cnt1; j--) {
                    if (dp[i - cnt0][j - cnt1] == -1) continue;
                    dp[i][j] = max(dp[i][j], dp[i - cnt0][j - cnt1] + 1);
                }
        }
        return dp[m][n];
    }
};

重点思路

可以参考【LeetCode-322】零钱兑换,只不过该问题为01背包,这个零钱兑换问题为完全背包。我们使用-1来初始化数组,然后将dp[0][0]设为0作为初始状态,当dp[i][j] = -1时,代表已遍历的元素中不存在刚好含有i个0和j个1的组合,则直接跳过即可。

标签:int,strs,cnt1,cnt0,494,--,LeetCode,dp
来源: https://www.cnblogs.com/tmpUser/p/14610902.html