Greedy algorithm: learning summary, and python code implementation of change problem

1. Greedy Algorithm

(1) The so-called greedy algorithm means that when solving a problem, it always makes the best choice in the current view. In other words, without considering the overall optimality, what he made is only a local optimal solution in a certain sense.
(2) Greedy algorithm does not get the overall optimal solution to all problems. The selected greedy strategy must have no aftereffect, that is, the process after a certain state will not affect the previous state, but is only related to the current state.

2. Conditions for the application of the greedy algorithm

(1) Applicable premise: the local optimal strategy can lead to the global optimal solution.
Generally, to analyze whether a problem is suitable for greedy algorithms, you can first select several actual data under the problem to analyze, and then you can make a judgment.

3. Example—Minimum number of change coins

(1) Greedy algorithm

def changegdal(totalmoney):       #找零算法,一共用25、10、1三种面币大小
    numcoins = 0
    if totalmoney >= 25:
        numcoins += totalmoney // 25
        totalmoney = totalmoney % 25
        print(f'25分找了{numcoins}个')

    if totalmoney >= 10:
        numcoins += totalmoney // 10
        print(f'10分找了{totalmoney//10}个')
        totalmoney = totalmoney % 10

    if totalmoney > 0 & totalmoney < 10:
        numcoins += totalmoney
        print(f'1分找了{totalmoney}个')

    print(f'一共找硬币{numcoins}个')


changegdal(3)

(2) Recursive call:

import time

def recMC(coinValueList, change):
    minCoins = change
    if change in coinValueList:
        return 1
    else:
        for i in [c for c in coinValueList if c <= change]:
            numCoins = 1 + recMC(coinValueList, change - i)     #加1,是因为后边调用自身减去了一个硬币
            if numCoins < minCoins:
                minCoins = numCoins
        return minCoins

def recDC(coinValueList, change, knownResults):
    minCoins = change
    if change in coinValueList:     #递归基本结束条件
        knownResults[change] = 1    #记录最优解
        return 1
    elif knownResults[change] > 0:
        return knownResults[change] #查表成功,直接返回最优解
    else:
        for i in [c for c in coinValueList if c <= change]:
            numCoins = 1 + recDC(coinValueList, change - i, knownResults)
            if numCoins < minCoins:
                minCoins = numCoins
                knownResults[change] = minCoins
    return minCoins


if __name__ == '__main__':
    #print(time.perf_counter())          #python3.8不推荐使用time.clock
    #print(recMC([1, 5, 10, 25], 63)
    #print(time.perf_counter())

    print(time.perf_counter())          #python3.8不推荐使用time.clock
    print(recDC([1, 5, 10, 25], 63, [0]*64))
    print(time.perf_counter())          #


Guess you like

Origin blog.csdn.net/qq_40797015/article/details/115186412