mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-14 16:16:06 +00:00
Release Rust code to documents. (#656)
This commit is contained in:
@@ -119,6 +119,14 @@
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="fractional_knapsack.rs"
|
||||
[class]{Item}-[func]{}
|
||||
|
||||
[class]{}-[func]{fractional_knapsack}
|
||||
```
|
||||
|
||||
最差情况下,需要遍历整个物品列表,**因此时间复杂度为 $O(n)$** ,其中 $n$ 为物品数量。
|
||||
|
||||
由于初始化了一个 `Item` 对象列表,**因此空间复杂度为 $O(n)$** 。
|
||||
|
||||
@@ -85,6 +85,12 @@
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="coin_change_greedy.rs"
|
||||
[class]{}-[func]{coin_change_greedy}
|
||||
```
|
||||
|
||||
## 贪心优点与局限性
|
||||
|
||||
**贪心算法不仅操作直接、实现简单,而且通常效率也很高**。在以上代码中,记硬币最小面值为 $\min(coins)$ ,则贪心选择最多循环 $amt / \min(coins)$ 次,时间复杂度为 $O(amt / \min(coins))$ 。这比动态规划解法的时间复杂度 $O(n \times amt)$ 提升了一个数量级。
|
||||
|
||||
@@ -143,6 +143,12 @@ $$
|
||||
[class]{}-[func]{maxCapacity}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="max_capacity.rs"
|
||||
[class]{}-[func]{max_capacity}
|
||||
```
|
||||
|
||||
### 正确性证明
|
||||
|
||||
之所以贪心比穷举更快,是因为每轮的贪心选择都会“跳过”一些状态。
|
||||
|
||||
@@ -129,6 +129,12 @@ $$
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
```rust title="max_product_cutting.rs"
|
||||
[class]{}-[func]{max_product_cutting}
|
||||
```
|
||||
|
||||

|
||||
|
||||
**时间复杂度取决于编程语言的幂运算的实现方法**。以 Python 为例,常用的幂计算函数有三种:
|
||||
|
||||
Reference in New Issue
Block a user