• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2016-01-17 06:01  neverlandly  阅读(502)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3