Backpack with Value array:
note that: "And the number of these merchandises can be considered as infinite."
function:
dp[i] |= dp[i - nums[j] * k]; (when you take that ith item)
or
dp[i] = false; (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 n: the money you have | |
* @return: the minimum money you have to give | |
*/ | |
public int backPackX(int target) { | |
// write your code here | |
if (target == 0) { | |
return 0; | |
} | |
boolean[] dp = new boolean[target + 1]; | |
// dp: init | |
dp[0] = true; | |
// dp: states + functions | |
int maximum = Integer.MIN_VALUE; | |
int[] nums = new int[]{150, 250, 350}; | |
for (int i = 1; i <= target; i++) { | |
for (int j = 0; j <= 2; j++) { | |
int k = 1; | |
while (i >= nums[j] * k) { | |
dp[i] |= dp[i - nums[j] * k]; | |
k++; | |
} | |
} | |
if (dp[i]) { | |
maximum = i; | |
} | |
} | |
// dp: answer | |
return target - maximum; | |
} | |
} |