You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 1385cc6
Browse filesBrowse the repository at this point in the historyBrowse files
dp[0][0] = 0; // 0 item, fills size 0, and of course value -> 0
43
+
44
+
Return:
45
+
dp[A.length][m]
46
+
47
+
Note:
48
+
when creating dp, we do (A.length + 1) for row size, simply because we get used to checking A[i-1] for prevous record ... Just keep this style. Don't get confused.
49
+
*/
50
+
51
+
52
+
publicclassSolution {
53
+
/**
54
+
* @param m: An integer m denotes the size of a backpack
55
+
* @param A & V: Given n items with size A[i] and value V[i]
56
+
* @return: The maximum value
57
+
*/
58
+
publicintbackPackII(intm, int[] A, intV[]) {
59
+
if (A == null || V == null || A.length == 0 || V.length == 0 || A.length != V.length || m <= 0) {
60
+
return0;
61
+
}
62
+
int[][] dp = newint[A.length + 1][m + 1];
63
+
dp[0][0] = 0; // 0 item, to make pack size = 0, of course value = 0.
Well, I kind of forgot about how we did this in algorithm class, but here we go, after a bit research:
22
94
DP[i][j] means: if i number of items in A, can we fill the bag size of j? Then, save a boolean in DP[i][j]. That means, if i items are too much for j?
23
95
24
96
So, there are two cases:
25
97
1. A[i] is unfortunately too big to fit into size j, so skip item A[i] and use DP[i-1][j].
26
98
2. OR, the other case: A[i] fits in well. We realize 2 things:
27
-
a. first (i-1)th items much fit in well into the bag size of (j - A[i - 1]): DP[i-1][j - A[i-1]]. Basically says items must be fit in (true) before adding A[i]
28
-
b. AND (j - A[i - 1]) must >= 0 to have space for next item i.
99
+
a. first (i-1)th items much fit in well into the bag size of (j - A[i - 1]): DP[i-1][j - A[i-1]]. Basically says items must be fit in (true) before adding A[i]
100
+
b. AND (j - A[i - 1]) must >= 0 to have space for next item i.
29
101
30
102
End:
31
103
Iterate through j:(m ~ 0), and return j, if DP[A.length][j] is true. We are starting from m, because we need the largest number j.
0 commit comments