贪婪算法
- 每步均选择局部的最优解,重复此过程,最终即得到全局的最优解
- 简而言之就是每步都采用最优解
优点:
- 简单易行
缺点:
- 并非在所有情况下都奏效
经典的问题:
- 背包问题
- 集合覆盖问题
贪婪算法下的近似算法解决集合覆盖问题
states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"])
stations = {}
stations["kone"] = set(["id", "nv", "ut"])
stations["ktwo"] = set(["wa", "id", "mt"])
stations["kthree"] = set(["or", "nv", "ca"])
stations["kfour"] = set(["nv", "ut"])
stations["kfive"] = set(["ca", "az"])
final_stations = set()
while states_needed:
best_station = None
states_covered = set()
for station, states in stations.items():
covered = states_needed & states
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
states_needed -= states_covered
final_stations.add(best_station)
print(final_stations)
原文地址:https://www.cnblogs.com/huang-yc/p/10322363.html
时间: 2024-11-05 22:05:57