xinyu04

导航

LeetCode 474 Ones and Zeroes 滚动数组优化DP

You are given an array of binary strings strs and two integers m and n.

Return the size of the largest subset of strs such that there are at most m \(0\)'s and n \(1\)'s in the subset.

A set \(x\) is a subset of a set \(y\) if all elements of \(x\) are also elements of \(y\).

Solution

考虑朴素的转移,设 \(dp[i][j][k]\) 表示在前 \(i\) 个字符串中,\(0\) 个数上限为 \(j\)\(1\) 个数上限为 \(k\) 时的最大子集个数。那么如何转移呢?类似于背包问题:我们或者不选当前的,也就是从上一层继承答案;或者选择当前的,进行答案的更新:

\[dp[i][j][k] = \max(dp[i-1][j][k],dp[i][j-n_0][k-n_1]+1) \]

其中 \(n_0,n_1\) 分别代表当前串中 \(0,1\) 的个数。

观察一下,我们此时的答案,只需要从上一层转移。所以用滚动数组来滚去一维。但此时需要注意的是,我们需要倒序来更新,否则就会将之前的上一层给抹去。

点击查看代码
class Solution {
private:
    int dp[102][102];
public:
    int findMaxForm(vector<string>& strs, int m, int n) {
        int l = strs.size();
        for(int i=0;i<l;i++){
            int n0 = 0, n1 = 0;
            for(int j=0;j<strs[i].length();j++){
                if(strs[i][j]=='0')n0++;
                else n1++;
            }
            for(int j=m;j>=n0;j--){
                for(int k=n;k>=n1;k--){
                    dp[j][k] = max(dp[j][k], dp[j-n0][k-n1]+1);
                }
            }
        }
        return dp[m][n];
    }
};

posted on 2022-06-04 20:13  Blackzxy  阅读(22)  评论(0编辑  收藏  举报