Skip to content

Commit

Permalink
Update 02.Algorithm-Complexity.md
Browse files Browse the repository at this point in the history
  • Loading branch information
itcharge committed Jan 10, 2022
1 parent 8d2eb7b commit 2812680
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions Contents/00.Introduction/02.Algorithm-Complexity.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,16 +162,21 @@ def algorithm(n):

#### 2.3.4 阶乘 $O(n!)$

阶乘时间复杂度一般出现在与「全排列」相关的算法中。这类算法随着问题规模 n 的增大,对应计算次数呈阶乘关系增长。
阶乘时间复杂度一般出现在与「全排列」、「旅行商问题暴力解法」相关的算法中。这类算法随着问题规模 n 的增大,对应计算次数呈阶乘关系增长。

```Python
def algorithm(n):
if n <= 0:
return 1
return n * algorithm(n - 1)
def permutations(arr, start, end):
if start == end:
print(arr)
return

for i in range(start, end):
arr[i], arr[start] = arr[start], arr[i]
permutations(arr, start + 1, end)
arr[i], arr[start] = arr[start], arr[i]
```

上述代码中计算阶乘使用了递归的方法。计算 `n` 的阶乘时需要先计算出 `n - 1` 的阶乘,计算 `n - 1` 的阶乘时,需要计算出 `n - 2` 的阶乘,以此类推。在计算总的时间复杂度时需要将每一步的基本操作数相乘,即:$n * (n - 1) * (n - 2) * ... * 2 * 1 = n!$,这段代码的执行次数为 $n!$ 次,所以其时间复杂度为 $O(n!)$。
上述代码中实现「全排列」使用了递归的方法。假设数组 `arr` 长度为 `n`,第一层 `for` 循环执行了 `n` 次,第二层 `for` 循环执行了 `n - 1` 次。以此类推,最后一层 `for` 循环执行了 `1` 次,将所有层 `for` 循环的执行次数累乘起来为 $n * (n - 1) * (n - 2) * ... * 2 * 1 = n!$ 次。则整个算法的 `for` 循环中基本语句的执行次数为 $n!$ 次,所以对应时间复杂度为 $O(n!)$。

#### 2.3.5 对数 $O(log_2n)$

Expand Down Expand Up @@ -302,4 +307,3 @@ def algorithm(n):
- 【文章】[算法复杂度(时间复杂度+空间复杂度)](https://www.biancheng.net/algorithm/complexity.html)
- 【文章】[算法基础 - 复杂度 - OI Wiki](https://oi-wiki.org/basic/complexity/)
- 【文章】[图解算法数据结构 - 算法复杂度 - LeetBook - 力扣](https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/r84gmi/)

0 comments on commit 2812680

Please sign in to comment.