三种硬币,2元、5元、7元,每种硬币足够多,买一本书需要27元,用最少的硬币组合
package com.fenxiangbuy.scm.xdtools.common.utils;
import cn.hutool.core.util.NumberUtil;
/**
* @Description TODO
* @Date 2021/3/23 14:23
* @Created by renchengpeng
*/
public class Test {
public static void main(String[] args) {
/**
* f(x) = 组成x币值需要的最少硬币数量
* f(x)=min(f(x-2),f(x-5),f(x-7))+1
*
* x-2 小于0 =====》-1
* f(x)无法组成===》-1
* [0,-1,1,-1,2,1,3,1,4,2,2,3,2,4,2,5,3,3,4,3,5,3,6,4,4,5,4,6]
*/
Integer[] coinCountArr = new Integer[28];
coinCountArr[0] = 0;
for (int coinIndex = 1; coinIndex < coinCountArr.length; coinIndex++) {
if (coinIndex < 2) {
coinCountArr[coinIndex] = -1;
}
coinCountArr[coinIndex] = getCoinCount(coinCountArr, coinIndex);
}
System.out.println(JsonUtil.bean2Json(coinCountArr));
}
private static Integer getCoinCount(Integer[] coinCountArr, int coin) {
Integer count7 = coin >= 7 && coinCountArr[coin - 7] != -1 ? coinCountArr[coin - 7] + 1 : Integer.MAX_VALUE;
Integer count5 = coin >= 5 && coinCountArr[coin - 5] != -1 ? coinCountArr[coin - 5] + 1 : Integer.MAX_VALUE;
Integer count2 = coin >= 2 && coinCountArr[coin - 2] != -1 ? coinCountArr[coin - 2] + 1 : Integer.MAX_VALUE;
Integer min = NumberUtil.min(count2, count5, count7);
return min.equals(Integer.MAX_VALUE) ? -1 : min;
}
}