随笔 - 171  文章 - 0  评论 - 0  阅读 - 62466

优惠叠加单元的所有子叠加单元

求取给定优惠叠加单元的所有子叠加单元。比如优惠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 +
                '}';
    }
}
复制代码

 

posted on   zhengbiyu  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示