【0-1 knapsack】 474. Ones and Zeroes

来源:互联网 发布:房子短租软件 编辑:程序博客网 时间:2024/06/02 05:43

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.

解题思路:
0/1背包问题的变种,用二维变量来表示背包的容量,即0和1的数量值。

  1. 统计各个字符串中0和1的数量
  2. 对于满足数量要求的背包元素,即dp[i][j],从大到小迭代更新dp[i][j]值
  3. 最后的dp[m][n]值即为最多可容纳的字符串数量值
class Solution(object):    def findMaxForm(self, strs, m, n):        dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]        for s in strs:            c0 = 0            c1 = 0            for c in s:                if c == "0":                    c0 += 1                else:                    c1 += 1            for i in range(m, c0 - 1, -1):                for j in range(n, c1 - 1, -1):                    dp[i][j] = max(dp[i - c0][j - c1] + 1, dp[i][j])        return dp[m][n]
0 0