求取給定優惠疊加單元的所有子疊加單元。比如優惠A減3元,優惠B減2元,優惠C減1元,優惠A、B、C都可以疊加,在下單頁優惠元件預設選中的是優惠A+優惠B+優惠C(共減6元),元件下拉框中同時存在優惠A+優惠B(共減5元)、優惠A+優惠C(共減4元)、優惠B+優惠C(共減3元)、優惠A(共減3元)、優惠B(共減2元)、優惠C(共減1元),使用者可以選擇優惠組合並進行切換,以上例子輸入ABC,返回AB、AC、BC、A、B、C。
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 求取給定優惠疊加單元的所有子疊加單元。比如優惠A減3元,優惠B減2元,優惠C減1元,優惠A、B、C都可以疊加, * 在下單頁優惠元件預設選中的是優惠A+優惠B+優惠C(共減6元),元件下拉框中同時存在優惠A+優惠B(共減5元)、優惠A+優惠C(共減4元)、 * 優惠B+優惠C(共減3元)、優惠A(共減3元)、優惠B(共減2元)、優惠C(共減1元),使用者可以選擇優惠組合並進行切換, * 以上例子輸入ABC,返回AB、AC、BC、A、B、C */ public class CouponTest { private static List<List<Coupon>> couponCombinationStrategy = new ArrayList<>(); //回溯演算法的遞迴路徑 private static LinkedList<Coupon> trackCouponCombination = new LinkedList<>(); public static void main(String[] args) { Coupon a = new Coupon("A", 3); Coupon b = new Coupon("B", 2); Coupon c = new Coupon("C", 1); List<Coupon> couponList = new ArrayList<>(); couponList.add(a); couponList.add(b); couponList.add(c); calculateCouponCombinationStrategy(couponList, 0); for (List<Coupon> coupons : couponCombinationStrategy) { for (Coupon coupon : coupons) { System.out.print(coupon); } System.out.println(); } } private static void calculateCouponCombinationStrategy(List<Coupon> couponList, int start) { if (trackCouponCombination.size() != couponList.size()) { couponCombinationStrategy.add(new ArrayList<>(trackCouponCombination)); } for (int i = start; i < couponList.size(); i++) { trackCouponCombination.add(couponList.get(i)); calculateCouponCombinationStrategy(couponList, i + 1); trackCouponCombination.removeLast(); } } } class Coupon { private String code; private int amount; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public Coupon(String code, int amount) { this.code = code; this.amount = amount; } @Override public String toString() { return "Coupon{" + "code='" + code + '\'' + ", amount=" + amount + '}'; } }