Backpack with Value array:
note that: "Each item may be chosen unlimited number of times"
function:
dp[i][j] += dp[i - 1][j - A[i - 1] * k]; (when you take that ith item)
or
dp[i][j] += dp[i - 1][j]; (when you don't take that ith item)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param nums: an integer array and all positive numbers, no duplicates | |
* @param target: An integer | |
* @return: An integer | |
*/ | |
public int backPackIV(int[] A, int m) { | |
// write your code here | |
if (A == null || A.length == 0) { | |
return 0; | |
} | |
int n = A.length; | |
// init | |
int[][] dp = new int[n+1][m+1]; | |
dp[0][0] = 1; | |
for (int j = 1; j <= m; j++) { | |
dp[0][j] = 0; | |
} | |
// dp: functions | |
int maximumJ = Integer.MIN_VALUE; | |
for (int i = 1; i <= n; i++) { | |
dp[i][0] = 1; | |
for (int j = 1; j <= m; j++) { | |
dp[i][j] = dp[i - 1][j]; | |
int k = 1; | |
while (j - A[i-1] * k >= 0) { | |
dp[i][j] += dp[i - 1][j - A[i - 1] * k]; | |
k++; | |
} | |
} | |
} | |
// dp: answer | |
return dp[n][m]; | |
} | |
} |
No comments:
Post a Comment