474. Ones and Zeroes

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了474. Ones and Zeroes相关的知识,希望对你有一定的参考价值。

There is an array filled with strings, each string is composed with ‘0‘ and ‘1‘. Given m ‘0‘ and n ‘1‘, return maximum number of strings can we compose using the given ones and zeros.

Solution O(K(L+MN)) K: array length, L:string length:

0-1 backpack problem(not understand).

1. Count how many ‘0‘ and how many ‘1‘ in each string, store them into count[0] & count[1].

2. Initialize a dp[m+1][n+1], and the return value is stored in dp[m][n].

    *dp[i][j] means if we have i ‘0‘ and j ‘1‘, maximum number of strings stored

3. Start from i = m, j = n, end with i = count[0], j = count[1], each time compare dp[i][j] & dp[i-count[0],j-count[1]]. 

    *This means if the string is put into the backpack, if or not the value will increase.

    Q: Why should we start from the end?

技术分享
 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 s : strs) {
 5             int[] num = findNumberOfZeroOne(s);
 6             for(int i = m; i >= num[0]; i--) {
 7                 for(int j = n; j >= num[1]; j--) {
 8                     dp[i][j] = Math.max(dp[i][j], 1+dp[i-num[0]][j-num[1]]);
 9                 }
10             }
11         }
12         return dp[m][n];
13     }
14     
15     private int[] findNumberOfZeroOne(String s) {
16         int[] num = new int[2];
17         for(int i = 0; i < s.length(); i++) {
18             char c = s.charAt(i);
19             if(c == ‘0‘) num[0]++;
20             if(c == ‘1‘) num[1]++;
21         }
22         return num;
23     }
24 }
View Code

 

以上是关于474. Ones and Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

474. Ones and Zeroes

474. Ones and Zeroes

[leetcode-474-Ones and Zeroes]

[Algorithm] 474. Ones and Zeroes

算法: 1和0子集合的个数 474. Ones and Zeroes

leetcode 474. Ones and Zeroes 一和零(中等)