算法的基本概念

1. 算法概念

algorithm:一個計算過程,解決問題的方法
程序設計=數據結構+算法
輸入→算法→輸出
數據結構就是關係python

2. 時間複雜度

用來估計算法運行時間的一個式子,通常來講時間複雜度高的算法比複雜度低的算法慢算法

2.1 一些例子:

print('hello')   # O1  無循環

for i in range(n):  # O(n)  一層循環
    print('hello')

for i in range(n):  # O(n2)  2層循環
    for j in range(n):
        print('hello')

while n > 1:  # O(logn)  每次循環減半
    print(n)
    n = n//2

2.2 時間複雜度排序

2.3 快速判斷算法複雜度

  • 肯定問題規模n
  • 是否循環減半→logn
  • k層關於n的循環→n^k

3. 空間複雜度

用來評估算法內存佔用大小的式子數據結構

  • 算法使用了幾個變量:O(1)
  • 算法使用了長度爲n的一維列表:O(n)
  • 算法使用了m行n列的二維列表:O(mn)
    能夠用空間換時間

4. 遞歸

遞歸的兩個特色函數

  • 調用自身
  • 結束條件
def func1(x):
    if x > 0:
        print(x)
        func1(x - 1)
# 3 2 1
def func2(x):
    if x > 0:
        func2(x - 1)
        print(x)
# 1 2 3

對上述結果的解釋設計

  1. func1的執行順序,窄的表示打印,寬的表示函數

    先打印在調用自身,從上到下執行下來
  2. func2的執行順序,窄的表示打印,寬的表示函數

    函數仍是從上往下執行,每一層都是先遞歸後打印,先打印的是最裏面那層遞歸

5. 漢諾塔問題

5.1 問題分析

  1. n=2時
    • 小圓盤從A移動到B
    • 大圓盤從A移動到C
    • 小圓盤從B移動到C
  2. n時候,上面n-1個盤子當作一個總體
    • 把n-1個盤子從A通過C移動到B
    • 把n個盤子從A移動到C
    • 把n-1個盤子從B通過A移動到C
def hanoi(n, a, b, c):
    '''
    一共n層,盤子從a通過b移動到c
    '''
    if n > 0:
        hanoi(n - 1, a, c, b)
        print('moving from %s to %s' % (a, c))
        hanoi(n - 1, b, a, c)

hanoi(3,'A','B','C')
'''
moving from A to C
moving from A to B
moving from C to B
moving from A to C
moving from B to A
moving from B to C
moving from A to C
'''
相關文章
相關標籤/搜索