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 ofm
0s
andn1s
respectively. On the other hand, there is an array with strings consisting of only0s
and1s
.Now your task is to find the maximum number of strings that you can form with givenm
0s
andn1s
. Each0
and1
can be used at mostonce.
Thoughts
看到按序挑选并且每件物品最多只挑一次以求填满自然想到背包。与传统背包不同的是这里有两件物品要挑,于是用到三维数组。而且它要返回的是能填满的可能个数,不只是否能填满,因此还需要记录个数。让f[i][j][k]表示前i个数能填满j个0和k个1的最长长度。
Code
Analysis
Errors:
j和k的初始值要从0开始。不能从s[i][0]和s[i][1]开始。因为记录的不是当前是否能填满,而是能填满的最长长度,即使当前str不能用于填满,它的长度也至少是f[i-1][j][k]. 同样不能从1开始,因为像[0][1]这样很重要的情况没有考虑,不像二维只要考虑[0]就可以了。
三重循环,时间复杂度是O(lmn).
Ver.2
Last updated
Was this helpful?