给你一部分钱和一些不同价钱的商品,如何在最多买K件商品的情况下尽可能多的花掉手里的钱。
举例:口袋里的钱数: 10; K=2 产品价格: [3, 6, 8, 7, 9] 输出 3, 7
Backtracking:
package BuyGoods;
import java.util.*; public class Solution {
static int minRemain = 0; public ArrayList<Integer> optimize(int money, int[] prices, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<Integer> path = new ArrayList<Integer>();
minRemain = money;
helper(result, path, money, prices, 0, k);
return result;
} public void helper(ArrayList<Integer> result, ArrayList<Integer> path, int remain, int[] prices, int pos, int times) {
if (remain < 0 || times<0) return;
if (remain < minRemain) {
minRemain = remain;
result.clear();
result.addAll(path);
}
for (int i=pos; i<prices.length; i++) {
path.add(prices[i]);
helper(result, path, remain-prices[i], prices, i+1, times-1);
path.remove(path.size()-1);
} } /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution sol = new Solution();
ArrayList<Integer> result = sol.optimize(10, new int[]{7,8,1,6,9}, 3);
System.out.println(result);
} }