G面经prepare: BuyGoods

给你一部分钱和一些不同价钱的商品,如何在最多买K件商品的情况下尽可能多的花掉手里的钱。
举例:口袋里的钱数: 10;   K=2     产品价格: [3, 6, 8, 7, 9]   输出 3, 7

Backtracking:

 1 package BuyGoods;
 2 import java.util.*;
 3 
 4 public class Solution {
 5     static int minRemain = 0;
 6 
 7     public ArrayList<Integer> optimize(int money, int[] prices, int k) {
 8         ArrayList<Integer> result = new ArrayList<Integer>();
 9         ArrayList<Integer> path = new ArrayList<Integer>();
10         minRemain = money;
11         helper(result, path, money, prices, 0, k);
12         return result;
13     }
14     
15     public void helper(ArrayList<Integer> result, ArrayList<Integer> path, int remain, int[] prices, int pos, int times) {
16         if (remain < 0 || times<0) return;
17         if (remain < minRemain) {
18             minRemain = remain;
19             result.clear();
20             result.addAll(path);
21         }
22         for (int i=pos; i<prices.length; i++) {
23             path.add(prices[i]);
24             helper(result, path, remain-prices[i], prices, i+1, times-1);
25             path.remove(path.size()-1);
26         }
27         
28     }
29 
30     /**
31      * @param args
32      */
33     public static void main(String[] args) {
34         // TODO Auto-generated method stub
35         Solution sol = new Solution();
36         ArrayList<Integer> result = sol.optimize(10, new int[]{7,8,1,6,9}, 3);
37         System.out.println(result);
38     }
39 
40 }

 

你可能感兴趣的:(G面经prepare: BuyGoods)