Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
You can not divide any item into small pieces.
If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 5], so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7] so that we can fulfill the backpack.
You function should return the max size we can fill in the given backpack.
O(n x m) time and O(m) memory.
O(n x m) memory is also acceptable if you do not know how to optimize memory.
动规经典题目,用数组dp[i]表示书包空间为i的时候能装的A物品最大容量。两次循环,外部遍历数组A,内部反向遍历数组dp,若j即背包容量大于等于物品体积A[i],则取前i-1次循环求得的最大容量dp[j],和背包体积为j-A[i]时的最大容量dp[j-A[i]]与第i个物品体积A[i]之和即dp[j-A[i]]+A[i]的较大值,作为本次循环后的最大容量dp[i]。
注意dp[]的空间要给m+1,因为我们要求的是第m+1个值dp[m],否则会抛出OutOfBoundException。
Given n items with size A[i] and value V[i], and a backpack with size m. What's the maximum value can you put into the backpack?
You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.
Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 9.
O(n x m) memory is acceptable, can you do it in O(m) memory?
和BackPack I基本一致。依然是以背包空间为限制条件,所不同的是dp[j]取的是价值较大值,而非体积较大值。所以只要把dp[j-A[i]]+A[i]换成dp[j-A[i]]+V[i]就可以了。
Given n kind of items with size Ai and value Vi( each item has an infinite number available) and a backpack with size m. What's the maximum value can you put into the backpack?
You cannot divide item into small pieces and the total size of items you choose should smaller or equal to m.
Given 4 items with size [2, 3, 5, 7] and value [1, 5, 2, 4], and a backpack with size 10. The maximum value is 15.
Given n items with size nums[i] which an integer array and all positive numbers, no duplicates. An integer target denotes the size of a backpack. Find the number of possible fill the backpack.
Each item may be chosen unlimited number of times
Given candidate items [2,3,6,7] and target 7,
A solution set is:
[7] [2, 2, 3] return 2Given n items with size nums[i] which an integer array and all positive numbers. An integer target denotes the size of a backpack. Find the number of possible fill the backpack.
Each item may only be used once
Given candidate items [1,2,3,3,7] and target 7,
A solution set is:
[7] [1, 3, 3] return 2Given an integer array nums with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
The different sequences are counted as different combinations.
Given nums = [1, 2, 4], target = 4
The possible combination ways are:
[1, 1, 1, 1] [1, 1, 2] [1, 2, 1] [2, 1, 1] [2, 2] [4] return 6