python coin exchange (coin exchange event organized by the Faculty of Science)

Change coins

Time limit: 1Sec Memory limit: 128MB

题目描述

The Faculty of Science organizes a coin exchange event, assuming that there is a banknote with a face value of N (1 <= N <= 10), given two different changes: 1 yuan and 2 yuan, the number is unlimited. If you exchange this N-dollar note for change, how many different methods are there?
For example, a banknote with a face value of 4 has the following 5 ways of changing:
4 = 1 + 1 + 1 + 1 + 1
4 = 2 + 1 + 1
4 = 1 + 2 + 1
4 = 1 + 1 + 2
4 = 2 + 2
Programming uses recursive methods to solve the above problems.

Input

只有一个数N,代表纸币面值

Output

输出一个数,代表所有不同的兑换方法的总数

Sample input

4

Sample output

5

Solution 1: Simulation (Violence is a miracle)

N = int(input())
def dfs(N):
    if(N==0):
        return 1;
    count1 = 0
    count2 = 0
    if(N-1 >= 0):
        count1 = dfs(N - 1)
    if(N - 2 >= 0):
        count2 = dfs(N - 2)
    return count1 + count2
print(dfs(N))

The answer is:[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

We found that the value of the latter term is equal to the sum of the first two terms.
The dfs()function can be modified to:

def dfs(N):
    if N == 1:
        return 1
    if N == 2:
        return 2
    return dfs(N-1)+dfs(N-2)

Solution 2: Backpack with memory (efficiency improvement)

N = int(input())
#data列表记录已经算出过的值,避免重复计算
data = [0]*1001
def dfs(N):
    #data为全局变量,记录下来修改过的data列表的值
    global data
    if(data[N] != 0):
        return data[N]
    if(N == 1):
        return 1
    if(N == 2):
        return 2
    # 把算出来的值添加进data列表
    data[N] = dfs(N-1) + dfs(N-2)
    return dfs(N-1) + dfs(N-2)
print(dfs(N))

Solution 3: (Dynamic Programming-Coming Soon)

状态转移方程:f(n) = f(n-1) + f(n-2)

N = int(input())
def dp(N):
    data = [0,1,2]
    for i in range(3,N + 1):
        data.append(data[i-1] + data[i-2])
    return data[N]
print(dp(N))

Solution 4: Playing a watch (oj score artifact, specializing in all kinds of disobedience, time complexity O (1))

N = int(input())
data = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711]
print(data[N])
Published 22 original articles · praised 0 · visits 797

Guess you like

Origin blog.csdn.net/sjxgghg/article/details/105221515