zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    宋体freetype16和12号字无法正常显示
    Visual Studio 2015 自动生成 的大文件xxx.vc.db的删除问题
    PP助手上传失效
    freetype教程网址
    编译器发展
    静态与动态库文件
    makefile文件操作大全
    Unicode编码字符范围和具体文字
    Oracle用户被锁定解决方法
    oracle中rownum和row_number()
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5136746.html
Copyright © 2011-2022 走看看