Leetcode: Ones and Zeroes
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. Note: The given numbers of 0s and 1s will both not exceed 100 The size of given string array won't exceed 600. Example 1: Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 Output: 4 Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0” Example 2: Input: Array = {"10", "0", "1"}, m = 1, n = 1 Output: 2 Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
This is a 0/1 backpacking problem
The problem can be interpreted as: What's the max number of str
can we pick from strs
with limitation of m
"0"
s and n
"1"
s. Thus we can define dp[i][j]
stands for max number of str
can we pick from strs
with limitation of i
"0"
s and j
"1"
s. For each str
, assume it has a
"0"
s and b
"1"
s, we update the dp
array iteratively and set dp[i][j] = Math.max(dp[i][j], dp[i - a][j - b] + 1)
. So at the end, dp[m][n]
is the answer.
the optimal code refer to https://discuss.leetcode.com/topic/71417/java-iterative-dp-solution-o-mn-space/5
Time Complexity: O(kl + kmn), where k is the length of input string array and l is the average length of a string within the array.
Space Complexity: O(mn)
(My thinking: )This solution applies the 'dimension-reduction strategy', otherwise the space is O(mnk). The strategy is to reverse the scaning direction from end of the array to start.
1 public class Solution { 2 public int findMaxForm(String[] strs, int m, int n) { 3 int[][] dp = new int[m+1][n+1]; 4 for (String str : strs) { 5 int[] cost = count(str); 6 for (int i=m; i>=cost[0]; i--) { 7 for (int j=n; j>=cost[1]; j--) { 8 dp[i][j] = Math.max(dp[i-cost[0]][j-cost[1]]+1, dp[i][j]); 9 } 10 } 11 } 12 return dp[m][n]; 13 } 14 15 public int[] count(String str) { 16 int[] count = new int[2]; 17 for (int i=0; i<str.length(); i++) { 18 count[(int)(str.charAt(i)-'0')]++; 19 } 20 return count; 21 } 22 }