📂
CS-NoteBook
  • Introduction
  • CS144
    • concise introduction to Internet
      • 1.1 Networked Applications
      • 1.2 The 4 Layer Internet
      • 1.3 IP
      • 1.4 A Day in the Life of a Packet
      • 1.5 Principle: Packet Switching
      • 1.6 Principle:Layering
      • 1.7 Principle: Encapsulation
      • 1.8 Byte order and packet formats
      • 1.9 name and addresses:IPv4
      • 1.10 Longest Prefix Match for Link Layer
      • 1.11 Address Resolution Protocol(ARP)
      • 1.12 Summary
    • Transport Layer
      • 2.1 The TCP Service Model
      • 2.2 UDP service model
      • 2.3 ICMP(Internet Control Message Protocol 互联网报文控制协议)
      • 2.4 The End-to-End Principle
      • 2.5 Error Detection:3 schemes (Checksum,CRC and MAC)
      • 2.6 Finite State Machines(有限状态机)
      • 2.7 Flow Control
      • 2.8 Sliding window
      • 2.9 Retransmission Strategies
      • 2.10 TCP Header
      • 2.11 TCP Setup and Teardown
      • 2.12 Recap
    • Package Switching
      • 3.1 The history of Internet
      • 3.2 What is packet switching
      • [3.3 End-to-end delay and Queueing delay
      • 3.4 Playback Buffer(回放缓存区)
  • CS 61C
    • 1.4 C Memory Mangement, Usage
    • 1.5 Intro to Assembly Language, MIPS Intro
    • 1.5 extra bits operation
  • CS 61B
  • CS 61A
    • Function
    • Names
    • The Art of the Function
    • Control
    • Higher-Order Function
    • Recursive Function
    • List
    • Non-Local Assignment
    • Iterators
    • Objects
    • Data Abstraction
    • OOP
    • Inheritance
    • Representations
    • Decomposition
    • Scheme
    • Exceptions
    • Calculator
    • Interpreters
    • Declarative_Programming
    • Table
    • Aggregation
      • More_recursion
    • Databases
    • Distributed_Data
    • Tail Recursion
    • Exercises
      • lab00
      • lab01
      • hw01
      • tree Recursion example -- give Change
  • The Web DevelopMent Bootcamp
    • html5
    • css
    • bootstrap3
    • bootstrap4
    • javascript expression
    • javascript function
Powered by GitBook
On this page

Was this helpful?

  1. CS 61A
  2. Exercises

tree Recursion example -- give Change

考虑下面这个问题:如果给你半美元、四分之一美元、十美分、五美分和一美分,一美元有多少种找零的方式?更通常来说,我们能不能编写一个函数,使用一系列货币的面额,计算有多少种方式为给定的金额总数找零?

分析

  • 我们可以递归将给定金额的找零问题,归约为使用更少种类的硬币为更小的金额找零的问题。

  • 使用n种硬币找零的方式为:

    • without:使用所有除了第一种之外的硬币为a找零的方式

    • within:使用n种硬币为更小的金额a - d找零的方式,其中d是第一种硬币的面额。

  • 终止条件

    • 如果a正好是零,那么有一种找零方式。

    • 如果a小于零,那么有零种找零方式。

    • 如果n小于零,那么有零种找零方式。

>>> def count_change(a, kinds=(50, 25, 10, 5, 1)):
        """Return the number of ways to change amount a using coin kinds."""
        if a == 0:
            return 1
        if a < 0 or len(kinds) == 0:
            return 0

        d = kinds[0]
        return count_change(a, kinds[1:]) + count_change(a - d, kinds)

>>> count_change(100)
292
Previoushw01NextThe Web DevelopMent Bootcamp

Last updated 4 years ago

Was this helpful?