zoukankan      html  css  js  c++  java
  • SICP 实例 ExchangeMoney

    (define (first-denomination kinds-of-coin)
    (cond ((= kinds-of-coin 1) 1)
    ((= kinds-of-coin 2) 5)
    ((= kinds-of-coin 3) 10)
    ((= kinds-of-coin 4) 25)
    ((= kinds-of-coin 5) 50)))

    (define (cc amount kinds-of-coin)
    (cond ((= amount 0) 1)
    ((or (< amount 0) (= kinds-of-coin 0)) 0)
    (else (+ (cc amount
    (- kinds-of-coin 1))
    (cc (- amount
    (first-denomination kinds-of-coin))
    kinds-of-coin)))))

    (define (count-change amount)
    (cc amount 5))

    (count-change 100)

    Java实现:

    /**
    * Created by Ramble on 2017/11/22.
    */
    public class ExchangeMoney {

    public static int first_denomination(int kinds_of_coin) {
    switch (kinds_of_coin) {
    case 1: {
    return 1;
    }
    case 2: {
    return 5;

    }
    case 3: {
    return 10;

    }
    case 4: {
    return 25;

    }
    case 5: {
    return 50;

    }
    default:
    return 0;
    }

    }

    public static int cc(int amount, int kinds_of_coin) {
    if (amount==0) {
    return 1;
    } else if (amount<0||kinds_of_coin==0) {
    return 0;
    } else {
    return cc(amount, kinds_of_coin-1) + cc(amount - first_denomination(kinds_of_coin), kinds_of_coin);
    }
    }

    public static int count_change(int amount) {
    return cc(amount, 5);
    }

    public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    System.out.println(count_change(1000));
    long endTime = System.currentTimeMillis();
    System.out.println("程序运行时间:"+(endTime-startTime)+"ms");
    }
    }
  • 相关阅读:
    openstack o版本自动化脚本安装
    定时关机重启
    centos7.2 安装openstack
    Ubuntu 16.03 apt-get更换为国内阿里云源
    centos7 安装php7+mysql5.7+nginx+redis
    centos7 安装LNMP7
    多个路由器配置静态路由 简单
    puppet笔记
    MySQL备份与恢复实战案例及生产方案
    WAF:web应用防火墙
  • 原文地址:https://www.cnblogs.com/R4mble/p/7881868.html
Copyright © 2011-2022 走看看