Python贪婪算法
贪婪算法
- 每步均选择局部的最优解,重复此过程,最终即得到全局的最优解
- 简而言之就是每步都采用最优解
优点:
- 简单易行
缺点:
- 并非在所有情况下都奏效
经典的问题:
- 背包问题
- 集合覆盖问题
贪婪算法下的近似算法解决集合覆盖问题
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)
本文来自博客园,作者:YanceDev,转载请注明原文链接:https://www.cnblogs.com/yance-dev/p/10322363.html