Python贪婪算法

贪婪算法

  • 每步均选择局部的最优解,重复此过程,最终即得到全局的最优解
  • 简而言之就是每步都采用最优解

优点:

  • 简单易行

缺点:

  • 并非在所有情况下都奏效

经典的问题:

  1. 背包问题
  2. 集合覆盖问题

贪婪算法下的近似算法解决集合覆盖问题

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)

posted @ 2019-01-26 00:01  YanceDev  阅读(851)  评论(0编辑  收藏  举报