mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-15 21:20:58 +00:00
build
This commit is contained in:
@@ -40,45 +40,35 @@ status: new
|
||||
|
||||
我们建立了一个物品类 `Item` ,以便将物品按照单位价值进行排序。循环进行贪心选择,当背包已满时跳出并返回解。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="fractional_knapsack.java"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
int w; // 物品重量
|
||||
int v; // 物品价值
|
||||
```python title="fractional_knapsack.py"
|
||||
class Item:
|
||||
"""物品"""
|
||||
|
||||
public Item(int w, int v) {
|
||||
this.w = w;
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
def __init__(self, w: int, v: int):
|
||||
self.w = w # 物品重量
|
||||
self.v = v # 物品价值
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
double fractionalKnapsack(int[] wgt, int[] val, int cap) {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
Item[] items = new Item[wgt.length];
|
||||
for (int i = 0; i < wgt.length; i++) {
|
||||
items[i] = new Item(wgt[i], val[i]);
|
||||
}
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
Arrays.sort(items, Comparator.comparingDouble(item -> -((double) item.v / item.w)));
|
||||
// 循环贪心选择
|
||||
double res = 0;
|
||||
for (Item item : items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (double) item.v / item.w * cap;
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
def fractional_knapsack(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""分数背包:贪心"""
|
||||
# 创建物品列表,包含两个属性:重量、价值
|
||||
items = [Item(w, v) for w, v in zip(wgt, val)]
|
||||
# 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort(key=lambda item: item.v / item.w, reverse=True)
|
||||
# 循环贪心选择
|
||||
res = 0
|
||||
for item in items:
|
||||
if item.w <= cap:
|
||||
# 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v
|
||||
cap -= item.w
|
||||
else:
|
||||
# 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (item.v / item.w) * cap
|
||||
# 已无剩余容量,因此跳出循环
|
||||
break
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -121,35 +111,86 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="fractional_knapsack.py"
|
||||
class Item:
|
||||
"""物品"""
|
||||
```java title="fractional_knapsack.java"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
int w; // 物品重量
|
||||
int v; // 物品价值
|
||||
|
||||
def __init__(self, w: int, v: int):
|
||||
self.w = w # 物品重量
|
||||
self.v = v # 物品价值
|
||||
public Item(int w, int v) {
|
||||
this.w = w;
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
|
||||
def fractional_knapsack(wgt: list[int], val: list[int], cap: int) -> int:
|
||||
"""分数背包:贪心"""
|
||||
# 创建物品列表,包含两个属性:重量、价值
|
||||
items = [Item(w, v) for w, v in zip(wgt, val)]
|
||||
# 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort(key=lambda item: item.v / item.w, reverse=True)
|
||||
# 循环贪心选择
|
||||
res = 0
|
||||
for item in items:
|
||||
if item.w <= cap:
|
||||
# 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v
|
||||
cap -= item.w
|
||||
else:
|
||||
# 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (item.v / item.w) * cap
|
||||
# 已无剩余容量,因此跳出循环
|
||||
break
|
||||
return res
|
||||
/* 分数背包:贪心 */
|
||||
double fractionalKnapsack(int[] wgt, int[] val, int cap) {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
Item[] items = new Item[wgt.length];
|
||||
for (int i = 0; i < wgt.length; i++) {
|
||||
items[i] = new Item(wgt[i], val[i]);
|
||||
}
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
Arrays.sort(items, Comparator.comparingDouble(item -> -((double) item.v / item.w)));
|
||||
// 循环贪心选择
|
||||
double res = 0;
|
||||
for (Item item : items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (double) item.v / item.w * cap;
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="fractional_knapsack.cs"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
public int w; // 物品重量
|
||||
public int v; // 物品价值
|
||||
|
||||
public Item(int w, int v) {
|
||||
this.w = w;
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
double fractionalKnapsack(int[] wgt, int[] val, int cap) {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
Item[] items = new Item[wgt.Length];
|
||||
for (int i = 0; i < wgt.Length; i++) {
|
||||
items[i] = new Item(wgt[i], val[i]);
|
||||
}
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
Array.Sort(items, (x, y) => (y.v / y.w).CompareTo(x.v / x.w));
|
||||
// 循环贪心选择
|
||||
double res = 0;
|
||||
foreach (Item item in items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (double)item.v / item.w * cap;
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -190,6 +231,45 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="fractional_knapsack.swift"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
var w: Int // 物品重量
|
||||
var v: Int // 物品价值
|
||||
|
||||
init(w: Int, v: Int) {
|
||||
self.w = w
|
||||
self.v = v
|
||||
}
|
||||
}
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
func fractionalKnapsack(wgt: [Int], val: [Int], cap: Int) -> Double {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
var items = zip(wgt, val).map { Item(w: $0, v: $1) }
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort(by: { -(Double($0.v) / Double($0.w)) < -(Double($1.v) / Double($1.w)) })
|
||||
// 循环贪心选择
|
||||
var res = 0.0
|
||||
var cap = cap
|
||||
for item in items {
|
||||
if item.w <= cap {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += Double(item.v)
|
||||
cap -= item.w
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += Double(item.v) / Double(item.w) * Double(cap)
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="fractional_knapsack.js"
|
||||
@@ -263,102 +343,6 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="fractional_knapsack.c"
|
||||
[class]{Item}-[func]{}
|
||||
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="fractional_knapsack.cs"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
public int w; // 物品重量
|
||||
public int v; // 物品价值
|
||||
|
||||
public Item(int w, int v) {
|
||||
this.w = w;
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
double fractionalKnapsack(int[] wgt, int[] val, int cap) {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
Item[] items = new Item[wgt.Length];
|
||||
for (int i = 0; i < wgt.Length; i++) {
|
||||
items[i] = new Item(wgt[i], val[i]);
|
||||
}
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
Array.Sort(items, (x, y) => (y.v / y.w).CompareTo(x.v / x.w));
|
||||
// 循环贪心选择
|
||||
double res = 0;
|
||||
foreach (Item item in items) {
|
||||
if (item.w <= cap) {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += (double)item.v / item.w * cap;
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="fractional_knapsack.swift"
|
||||
/* 物品 */
|
||||
class Item {
|
||||
var w: Int // 物品重量
|
||||
var v: Int // 物品价值
|
||||
|
||||
init(w: Int, v: Int) {
|
||||
self.w = w
|
||||
self.v = v
|
||||
}
|
||||
}
|
||||
|
||||
/* 分数背包:贪心 */
|
||||
func fractionalKnapsack(wgt: [Int], val: [Int], cap: Int) -> Double {
|
||||
// 创建物品列表,包含两个属性:重量、价值
|
||||
var items = zip(wgt, val).map { Item(w: $0, v: $1) }
|
||||
// 按照单位价值 item.v / item.w 从高到低进行排序
|
||||
items.sort(by: { -(Double($0.v) / Double($0.w)) < -(Double($1.v) / Double($1.w)) })
|
||||
// 循环贪心选择
|
||||
var res = 0.0
|
||||
var cap = cap
|
||||
for item in items {
|
||||
if item.w <= cap {
|
||||
// 若剩余容量充足,则将当前物品整个装进背包
|
||||
res += Double(item.v)
|
||||
cap -= item.w
|
||||
} else {
|
||||
// 若剩余容量不足,则将当前物品的一部分装进背包
|
||||
res += Double(item.v) / Double(item.w) * Double(cap)
|
||||
// 已无剩余容量,因此跳出循环
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="fractional_knapsack.zig"
|
||||
[class]{Item}-[func]{}
|
||||
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="fractional_knapsack.dart"
|
||||
@@ -441,6 +425,22 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="fractional_knapsack.c"
|
||||
[class]{Item}-[func]{}
|
||||
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="fractional_knapsack.zig"
|
||||
[class]{Item}-[func]{}
|
||||
|
||||
[class]{}-[func]{fractionalKnapsack}
|
||||
```
|
||||
|
||||
最差情况下,需要遍历整个物品列表,**因此时间复杂度为 $O(n)$** ,其中 $n$ 为物品数量。
|
||||
|
||||
由于初始化了一个 `Item` 对象列表,**因此空间复杂度为 $O(n)$** 。
|
||||
|
||||
@@ -26,27 +26,24 @@ status: new
|
||||
|
||||
实现代码如下所示。你可能会不由地发出感叹:So Clean !贪心算法仅用十行代码就解决了零钱兑换问题。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="coin_change_greedy.java"
|
||||
/* 零钱兑换:贪心 */
|
||||
int coinChangeGreedy(int[] coins, int amt) {
|
||||
// 假设 coins 列表有序
|
||||
int i = coins.length - 1;
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
```python title="coin_change_greedy.py"
|
||||
def coin_change_greedy(coins: list[int], amt: int) -> int:
|
||||
"""零钱兑换:贪心"""
|
||||
# 假设 coins 列表有序
|
||||
i = len(coins) - 1
|
||||
count = 0
|
||||
# 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0:
|
||||
# 找到小于且最接近剩余金额的硬币
|
||||
while i > 0 and coins[i] > amt:
|
||||
i -= 1
|
||||
# 选择 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
# 若未找到可行方案,则返回 -1
|
||||
return count if amt == 0 else -1
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -72,24 +69,50 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="coin_change_greedy.py"
|
||||
def coin_change_greedy(coins: list[int], amt: int) -> int:
|
||||
"""零钱兑换:贪心"""
|
||||
# 假设 coins 列表有序
|
||||
i = len(coins) - 1
|
||||
count = 0
|
||||
# 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0:
|
||||
# 找到小于且最接近剩余金额的硬币
|
||||
while i > 0 and coins[i] > amt:
|
||||
i -= 1
|
||||
# 选择 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
# 若未找到可行方案,则返回 -1
|
||||
return count if amt == 0 else -1
|
||||
```java title="coin_change_greedy.java"
|
||||
/* 零钱兑换:贪心 */
|
||||
int coinChangeGreedy(int[] coins, int amt) {
|
||||
// 假设 coins 列表有序
|
||||
int i = coins.length - 1;
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="coin_change_greedy.cs"
|
||||
/* 零钱兑换:贪心 */
|
||||
int coinChangeGreedy(int[] coins, int amt) {
|
||||
// 假设 coins 列表有序
|
||||
int i = coins.Length - 1;
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -118,6 +141,30 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="coin_change_greedy.swift"
|
||||
/* 零钱兑换:贪心 */
|
||||
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
|
||||
// 假设 coins 列表有序
|
||||
var i = coins.count - 1
|
||||
var count = 0
|
||||
var amt = amt
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0 {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while i > 0 && coins[i] > amt {
|
||||
i -= 1
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="coin_change_greedy.js"
|
||||
@@ -164,65 +211,6 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="coin_change_greedy.c"
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="coin_change_greedy.cs"
|
||||
/* 零钱兑换:贪心 */
|
||||
int coinChangeGreedy(int[] coins, int amt) {
|
||||
// 假设 coins 列表有序
|
||||
int i = coins.Length - 1;
|
||||
int count = 0;
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while (amt > 0) {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="coin_change_greedy.swift"
|
||||
/* 零钱兑换:贪心 */
|
||||
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
|
||||
// 假设 coins 列表有序
|
||||
var i = coins.count - 1
|
||||
var count = 0
|
||||
var amt = amt
|
||||
// 循环进行贪心选择,直到无剩余金额
|
||||
while amt > 0 {
|
||||
// 找到小于且最接近剩余金额的硬币
|
||||
while i > 0 && coins[i] > amt {
|
||||
i -= 1
|
||||
}
|
||||
// 选择 coins[i]
|
||||
amt -= coins[i]
|
||||
count += 1
|
||||
}
|
||||
// 若未找到可行方案,则返回 -1
|
||||
return amt == 0 ? count : -1
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="coin_change_greedy.zig"
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="coin_change_greedy.dart"
|
||||
@@ -273,6 +261,18 @@ status: new
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="coin_change_greedy.c"
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="coin_change_greedy.zig"
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
```
|
||||
|
||||
## 15.1.1 贪心优点与局限性
|
||||
|
||||
**贪心算法不仅操作直接、实现简单,而且通常效率也很高**。在以上代码中,记硬币最小面值为 $\min(coins)$ ,则贪心选择最多循环 $amt / \min(coins)$ 次,时间复杂度为 $O(amt / \min(coins))$ 。这比动态规划解法的时间复杂度 $O(n \times amt)$ 提升了一个数量级。
|
||||
|
||||
@@ -93,29 +93,26 @@ $$
|
||||
|
||||
变量 $i$、$j$、$res$ 使用常数大小额外空间,**因此空间复杂度为 $O(1)$** 。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="max_capacity.java"
|
||||
/* 最大容量:贪心 */
|
||||
int maxCapacity(int[] ht) {
|
||||
// 初始化 i, j 分列数组两端
|
||||
int i = 0, j = ht.length - 1;
|
||||
// 初始最大容量为 0
|
||||
int res = 0;
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int cap = Math.min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.max(res, cap);
|
||||
// 向内移动短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```python title="max_capacity.py"
|
||||
def max_capacity(ht: list[int]) -> int:
|
||||
"""最大容量:贪心"""
|
||||
# 初始化 i, j 分列数组两端
|
||||
i, j = 0, len(ht) - 1
|
||||
# 初始最大容量为 0
|
||||
res = 0
|
||||
# 循环贪心选择,直至两板相遇
|
||||
while i < j:
|
||||
# 更新最大容量
|
||||
cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
# 向内移动短板
|
||||
if ht[i] < ht[j]:
|
||||
i += 1
|
||||
else:
|
||||
j -= 1
|
||||
return res
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -143,26 +140,54 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="max_capacity.py"
|
||||
def max_capacity(ht: list[int]) -> int:
|
||||
"""最大容量:贪心"""
|
||||
# 初始化 i, j 分列数组两端
|
||||
i, j = 0, len(ht) - 1
|
||||
# 初始最大容量为 0
|
||||
res = 0
|
||||
# 循环贪心选择,直至两板相遇
|
||||
while i < j:
|
||||
# 更新最大容量
|
||||
cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
# 向内移动短板
|
||||
if ht[i] < ht[j]:
|
||||
i += 1
|
||||
else:
|
||||
j -= 1
|
||||
return res
|
||||
```java title="max_capacity.java"
|
||||
/* 最大容量:贪心 */
|
||||
int maxCapacity(int[] ht) {
|
||||
// 初始化 i, j 分列数组两端
|
||||
int i = 0, j = ht.length - 1;
|
||||
// 初始最大容量为 0
|
||||
int res = 0;
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int cap = Math.min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.max(res, cap);
|
||||
// 向内移动短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="max_capacity.cs"
|
||||
/* 最大容量:贪心 */
|
||||
int maxCapacity(int[] ht) {
|
||||
// 初始化 i, j 分列数组两端
|
||||
int i = 0, j = ht.Length - 1;
|
||||
// 初始最大容量为 0
|
||||
int res = 0;
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int cap = Math.Min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.Max(res, cap);
|
||||
// 向内移动短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -190,6 +215,31 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="max_capacity.swift"
|
||||
/* 最大容量:贪心 */
|
||||
func maxCapacity(ht: [Int]) -> Int {
|
||||
// 初始化 i, j 分列数组两端
|
||||
var i = 0, j = ht.count - 1
|
||||
// 初始最大容量为 0
|
||||
var res = 0
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while i < j {
|
||||
// 更新最大容量
|
||||
let cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
// 向内移动短板
|
||||
if ht[i] < ht[j] {
|
||||
i += 1
|
||||
} else {
|
||||
j -= 1
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="max_capacity.js"
|
||||
@@ -242,68 +292,6 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="max_capacity.c"
|
||||
[class]{}-[func]{maxCapacity}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="max_capacity.cs"
|
||||
/* 最大容量:贪心 */
|
||||
int maxCapacity(int[] ht) {
|
||||
// 初始化 i, j 分列数组两端
|
||||
int i = 0, j = ht.Length - 1;
|
||||
// 初始最大容量为 0
|
||||
int res = 0;
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while (i < j) {
|
||||
// 更新最大容量
|
||||
int cap = Math.Min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.Max(res, cap);
|
||||
// 向内移动短板
|
||||
if (ht[i] < ht[j]) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="max_capacity.swift"
|
||||
/* 最大容量:贪心 */
|
||||
func maxCapacity(ht: [Int]) -> Int {
|
||||
// 初始化 i, j 分列数组两端
|
||||
var i = 0, j = ht.count - 1
|
||||
// 初始最大容量为 0
|
||||
var res = 0
|
||||
// 循环贪心选择,直至两板相遇
|
||||
while i < j {
|
||||
// 更新最大容量
|
||||
let cap = min(ht[i], ht[j]) * (j - i)
|
||||
res = max(res, cap)
|
||||
// 向内移动短板
|
||||
if ht[i] < ht[j] {
|
||||
i += 1
|
||||
} else {
|
||||
j -= 1
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="max_capacity.zig"
|
||||
[class]{}-[func]{maxCapacity}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="max_capacity.dart"
|
||||
@@ -355,6 +343,18 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="max_capacity.c"
|
||||
[class]{}-[func]{maxCapacity}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="max_capacity.zig"
|
||||
[class]{}-[func]{maxCapacity}
|
||||
```
|
||||
|
||||
### 3. 正确性证明
|
||||
|
||||
之所以贪心比穷举更快,是因为每轮的贪心选择都会“跳过”一些状态。
|
||||
|
||||
@@ -74,29 +74,24 @@ $$
|
||||
|
||||
请注意,对于 $n \leq 3$ 的边界情况,必须拆分出一个 $1$ ,乘积为 $1 \times (n - 1)$ 。
|
||||
|
||||
=== "Java"
|
||||
=== "Python"
|
||||
|
||||
```java title="max_product_cutting.java"
|
||||
/* 最大切分乘积:贪心 */
|
||||
int maxProductCutting(int n) {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return (int) Math.pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return (int) Math.pow(3, a) * 2;
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return (int) Math.pow(3, a);
|
||||
}
|
||||
```python title="max_product_cutting.py"
|
||||
def max_product_cutting(n: int) -> int:
|
||||
"""最大切分乘积:贪心"""
|
||||
# 当 n <= 3 时,必须切分出一个 1
|
||||
if n <= 3:
|
||||
return 1 * (n - 1)
|
||||
# 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
a, b = n // 3, n % 3
|
||||
if b == 1:
|
||||
# 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return int(math.pow(3, a - 1)) * 2 * 2
|
||||
if b == 2:
|
||||
# 当余数为 2 时,不做处理
|
||||
return int(math.pow(3, a)) * 2
|
||||
# 当余数为 0 时,不做处理
|
||||
return int(math.pow(3, a))
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
@@ -124,24 +119,54 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
=== "Java"
|
||||
|
||||
```python title="max_product_cutting.py"
|
||||
def max_product_cutting(n: int) -> int:
|
||||
"""最大切分乘积:贪心"""
|
||||
# 当 n <= 3 时,必须切分出一个 1
|
||||
if n <= 3:
|
||||
return 1 * (n - 1)
|
||||
# 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
a, b = n // 3, n % 3
|
||||
if b == 1:
|
||||
# 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return int(math.pow(3, a - 1)) * 2 * 2
|
||||
if b == 2:
|
||||
# 当余数为 2 时,不做处理
|
||||
return int(math.pow(3, a)) * 2
|
||||
# 当余数为 0 时,不做处理
|
||||
return int(math.pow(3, a))
|
||||
```java title="max_product_cutting.java"
|
||||
/* 最大切分乘积:贪心 */
|
||||
int maxProductCutting(int n) {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return (int) Math.pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return (int) Math.pow(3, a) * 2;
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return (int) Math.pow(3, a);
|
||||
}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="max_product_cutting.cs"
|
||||
/* 最大切分乘积:贪心 */
|
||||
int maxProductCutting(int n) {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return (int)Math.Pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return (int)Math.Pow(3, a) * 2;
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return (int)Math.Pow(3, a);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
@@ -169,6 +194,31 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="max_product_cutting.swift"
|
||||
/* 最大切分乘积:贪心 */
|
||||
func maxProductCutting(n: Int) -> Int {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if n <= 3 {
|
||||
return 1 * (n - 1)
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
let a = n / 3
|
||||
let b = n % 3
|
||||
if b == 1 {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return pow(3, a - 1) * 2 * 2
|
||||
}
|
||||
if b == 2 {
|
||||
// 当余数为 2 时,不做处理
|
||||
return pow(3, a) * 2
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return pow(3, a)
|
||||
}
|
||||
```
|
||||
|
||||
=== "JS"
|
||||
|
||||
```javascript title="max_product_cutting.js"
|
||||
@@ -219,68 +269,6 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="max_product_cutting.c"
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
```
|
||||
|
||||
=== "C#"
|
||||
|
||||
```csharp title="max_product_cutting.cs"
|
||||
/* 最大切分乘积:贪心 */
|
||||
int maxProductCutting(int n) {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
int a = n / 3;
|
||||
int b = n % 3;
|
||||
if (b == 1) {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return (int)Math.Pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b == 2) {
|
||||
// 当余数为 2 时,不做处理
|
||||
return (int)Math.Pow(3, a) * 2;
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return (int)Math.Pow(3, a);
|
||||
}
|
||||
```
|
||||
|
||||
=== "Swift"
|
||||
|
||||
```swift title="max_product_cutting.swift"
|
||||
/* 最大切分乘积:贪心 */
|
||||
func maxProductCutting(n: Int) -> Int {
|
||||
// 当 n <= 3 时,必须切分出一个 1
|
||||
if n <= 3 {
|
||||
return 1 * (n - 1)
|
||||
}
|
||||
// 贪心地切分出 3 ,a 为 3 的个数,b 为余数
|
||||
let a = n / 3
|
||||
let b = n % 3
|
||||
if b == 1 {
|
||||
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
|
||||
return pow(3, a - 1) * 2 * 2
|
||||
}
|
||||
if b == 2 {
|
||||
// 当余数为 2 时,不做处理
|
||||
return pow(3, a) * 2
|
||||
}
|
||||
// 当余数为 0 时,不做处理
|
||||
return pow(3, a)
|
||||
}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="max_product_cutting.zig"
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
```
|
||||
|
||||
=== "Dart"
|
||||
|
||||
```dart title="max_product_cutting.dart"
|
||||
@@ -331,6 +319,18 @@ $$
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
```c title="max_product_cutting.c"
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
```zig title="max_product_cutting.zig"
|
||||
[class]{}-[func]{maxProductCutting}
|
||||
```
|
||||
|
||||

|
||||
|
||||
<p align="center"> 图 15-16 最大切分乘积的计算方法 </p>
|
||||
|
||||
Reference in New Issue
Block a user