Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add a description of the solution to lcci problem: No.08.05 #761

Merged
merged 1 commit into from
Mar 20, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions lcci/08.05.Recursive Mulitply/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,59 @@

<!-- 这里可写通用的实现逻辑 -->

~~**最佳方案:**~~

~~直接返回 `A * B`~~

正常递归,叠加总和

```txt
MULTIPLY(A, B)
if A == 0 || B == 0
return 0
A + multiply(A, B - 1)
```

优化 1:

由数值较小的数字决定递归层次

```txt
MULTIPLY(A, B)
if A == 0 || B == 0
return 0
return max(A, B) + multiply(max(A, B), min(A, B) - 1)
```

优化 2:

使用位移减少递归层次

```txt
MULTIPLY(A, B)
return (B % 1 == 1 ? A : 0) + (B > 1 ? MULTIPLY(A + A, B >> 1) : 0)
```

可进一步,转换为循环,虽然并不符合递归主题。

> A 与 B 皆为**正整数**,初始值不会为 0,所以终止条件是 `B != 1`

```txt
MULTIPLY(A, B)
T = min(A, B)
A = max(A, B)
B = T
r = 0
while B != 1 {
if B % 2 == 1 {
r = r + A
}
A = A + A
B = B >> 1
}
return res + A
```

<!-- tabs:start -->

### **Python3**
Expand Down