一道计算付款组合方式的平安科技面试题

无意中看到一道平安科技2017年的面试题(根据消费者手上的钱计算所有可能的付款方式),想到几年前写过一篇博客《换零钱算法分析及代码示例》,似乎可以借鉴一下思路。先根据用户手中钱币种类计算出所有可能的换零钱方式,再根据用户持有的钱币数量判断这种付款方式是否有效。

一、面试题截图

这里写图片描述

这里写图片描述

二、解题思路

换零钱的思路是采用递归分解的思想,将某金额的钱币换成指定种类零钱的方式等价于换成必包含第一种钱币的零钱方式和必不包含第一种零钱方式的并集。详细的推导过程参看《换零钱算法分析及代码示例》,这里不详解。贴出源码:

1、钱币种类枚举定义

package com.elon;

/**
 * 钱币种类枚举定义。
 * 
 * @author elon
 * @version 2018年3月9日
 */
public enum EnumMoneyType {
    ONE_YUAN("a1", 1),

    FIVE_YUAN("a2", 5),

    TEEN_YUAN("a3", 10),

    TWENTY_YUAN("a4", 20),

    FIFTY_YUAN("a5", 50),

    HUNDRED_YUAN("a6", 100);

    /**
     * 币值类型
     */
    private String type;

    /**
     * 币值
     */
    private int value;

    public String getType() {
        return type;
    }

    public int getValue() {
        return value;
    }

    private EnumMoneyType(String type, int value) {
        this.type = type;
        this.value = value;
    }

    public static int getValueByType(String type)
    {
        EnumMoneyType[] values = EnumMoneyType.values();
        for (EnumMoneyType v : values) {
            if (v.type.equals(type)) {
                return v.value;
            }
        }

        return 0;
    }

    public static String getTypeByValue(int value) {
        EnumMoneyType[] values = EnumMoneyType.values();
        for (EnumMoneyType v : values) {
            if (v.value == value) {
                return v.type;
            }
        }

        return "";
    }
}

2、递归树子节点类型定义

package com.elon;

/**
 * 子节点类型。
 * 
 * @author elon
 * @version 2018年3月7日
 */
public enum EnumChildType {
    LEFT,   //左节点
    RIGHT;  //右节点
}

3、从控制台录入条件,解析条件

package com.elon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class StartService {
    public static void main(String[] args) {

        //从控制台读入输入的n=11,a1=0,a2=0,a3=5,a4=6,a5=3,a6=2
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try {
            String str = reader.readLine();
            String[] splitResults = str.split(",");

            //提取转换为Key/Value结构方便查询
            Map<String, Integer> keyValueMap = new HashMap<>();
            for (String pair : splitResults) {
                String[] pairValues = pair.split("=");
                keyValueMap.put(pairValues[0].trim(), Integer.parseInt(pairValues[1].trim()));
            }

            int total = keyValueMap.get("n");

            Map<Integer, Integer> moneyMap = new HashMap<>();
            moneyMap.put(EnumMoneyType.ONE_YUAN.getValue(), keyValueMap.get(EnumMoneyType.ONE_YUAN.getType()));
            moneyMap.put(EnumMoneyType.FIVE_YUAN.getValue(), keyValueMap.get(EnumMoneyType.FIVE_YUAN.getType()));
            moneyMap.put(EnumMoneyType.TEEN_YUAN.getValue(), keyValueMap.get(EnumMoneyType.TEEN_YUAN.getType()));
            moneyMap.put(EnumMoneyType.TWENTY_YUAN.getValue(), keyValueMap.get(EnumMoneyType.TWENTY_YUAN.getType()));
            moneyMap.put(EnumMoneyType.FIFTY_YUAN.getValue(), keyValueMap.get(EnumMoneyType.FIFTY_YUAN.getType()));
            moneyMap.put(EnumMoneyType.HUNDRED_YUAN.getValue(), keyValueMap.get(EnumMoneyType.HUNDRED_YUAN.getType()));

            List<Map<Integer, Integer>> resultList = new PaymentCalc().calcPaymentMethod(total, moneyMap);

            List<Map<String, Integer>> resultShowList = new ArrayList<>();
            for (Map<Integer, Integer> result : resultList) {
                Map<String, Integer> resultShowMap = new HashMap<>();
                for (Entry<Integer, Integer> entry : result.entrySet()) {
                    resultShowMap.put(EnumMoneyType.getTypeByValue(entry.getKey()), entry.getValue());
                }

                resultShowList.add(resultShowMap);
            }

            System.out.println("支持的付款方式(钱币种类=张数):" + resultShowList);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

4、计算及打印可能的付款组合方式

package com.elon;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;

/**
 * 计算支付方式。
 * 
 * @author elon
 * @version 2018年3月5日
 */
public class PaymentCalc {

    /**
     * 计算支持的付款方式。
     * 
     * @param totalMoney 总付款金额.
     * @param moneyMap 持有的钱币信息 .Map<币值分类, 数量>
     * @return 付款方式。List<Map<币值分类, 数量>>
     */
    public List<Map<Integer, Integer>> calcPaymentMethod(int totalMoney, Map<Integer, Integer> moneyMap){

        List<List<Integer>> payList = new ArrayList<List<Integer>>();
        List<Integer> currencyTypeList = new ArrayList<>();
        currencyTypeList.addAll(moneyMap.keySet());
        Collections.sort(currencyTypeList);

        payList = calcPayMethodByCurrency(totalMoney, currencyTypeList);
        return judgePayNum(payList, moneyMap);
    }

    /**
     * 根据币种计算所有可能的支付方式。
     * 
     * @param totalMoney 总金额
     * @param currencyList 币种列表
     * @return 支持的支付方式
     */
    private List<List<Integer>> calcPayMethodByCurrency(int totalMoney, List<Integer> currencyList){

        List<List<Integer>> payList = new ArrayList<List<Integer>>();

        //计算右子树
        Stack<Integer> payMethod = new Stack<>();
        payList.addAll(calcChildPayMethod(totalMoney - currencyList.get(0) , currencyList, payMethod, 
                EnumChildType.RIGHT));

        //计算左子树
        List<Integer> leftCurrencyTypeList = new ArrayList<>();
        leftCurrencyTypeList.addAll(currencyList);
        leftCurrencyTypeList.remove(0);
        payList.addAll(calcChildPayMethod(totalMoney, leftCurrencyTypeList, new Stack<Integer>(), 
                EnumChildType.LEFT));

        return payList;
    }

    /**
     * 递归计算子树节点。这个函数中没一步操作,入栈、出栈,判断处理的顺序都很重。
     * 
     * @param totalMoney 总金额
     * @param currencyList 币种数量列表
     * @param payMethod 支付方式列表
     * @param lOrR 当前处理的是左子树还是右子树
     * @return 支付方式列表
     */
    private List<List<Integer>> calcChildPayMethod(int totalMoney, List<Integer> currencyList,
            Stack<Integer> payMethod, EnumChildType lOrR) {

        List<List<Integer>> payList = new ArrayList<List<Integer>>();

        if (lOrR == EnumChildType.RIGHT && !currencyList.isEmpty()) {
            payMethod.push(currencyList.get(0));
        }

        if (totalMoney == 0) {
            List<Integer> payCopy = new ArrayList<>();
            payCopy.addAll(payMethod);
            payList.add(payCopy);
            return payList;
        }

        if (totalMoney < 0 || currencyList.isEmpty()) {
            return payList;
        }

        List<Integer> moneyTypeListLeft = new ArrayList<>();
        moneyTypeListLeft.addAll(currencyList);
        moneyTypeListLeft.remove(0);

        //递归处理右子树
        payList.addAll(calcChildPayMethod(totalMoney - currencyList.get(0), currencyList, payMethod, 
                EnumChildType.RIGHT));

        //由于上一步是最后处理右子树,且currencyList不为空,有入栈操作。执行完后需要 先出栈在处理左子树。
        payMethod.pop();

        //递归处理左子树
        payList.addAll(calcChildPayMethod(totalMoney, moneyTypeListLeft, payMethod, EnumChildType.LEFT));

        return payList;
    }

    /**
     * 根据手上持有的货币判断实际能支持哪些付费方式。
     * 
     * @param payList
     *            按币种计算所有可能的付费方式
     * @param moneyMap
     *            持久的货币信息
     * @return 实际支持的支付方式
     */
    private List<Map<Integer, Integer>> judgePayNum(List<List<Integer>> payList, Map<Integer, Integer> moneyMap) {

        List<Map<Integer, Integer>> fitPayMap = new ArrayList<>();
        List<Map<Integer, Integer>> allPayMap = new ArrayList<>();

        for (List<Integer> pay : payList) {

            Map<Integer, Integer> onePayMap = new HashMap<>();
            for (int money : pay) {
                if (!onePayMap.containsKey(money)) {
                    onePayMap.put(money, 0);
                }

                onePayMap.put(money, onePayMap.get(money) + 1);
            }

            allPayMap.add(onePayMap);
        }

        for (Map<Integer, Integer> payMap : allPayMap) {
            boolean bFit = true;
            for (Entry<Integer, Integer> entry : payMap.entrySet()) {
                if (!moneyMap.containsKey(entry.getKey()) || moneyMap.get(entry.getKey()) < entry.getValue()) {
                    bFit = false;
                    break;
                }
            }

            if (bFit) {
                fitPayMap.add(payMap);
            }
        }

        return fitPayMap;
    }
}

三、测试打印结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值