标签:number increase orm ack exp isp cat ges lock
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 }
标签:number increase orm ack exp isp cat ges lock
原文地址:http://www.cnblogs.com/CornerCase/p/6275859.html