greedy算法的核心思想是首先計算覆蓋面大的部分,而後依次尋找其餘覆蓋面最大的部分。該算法的使用場景就像他的名字同樣,當符合貪婪屬性的時候就能夠考慮。python
states_needed = set(['北京', '上海', '廣州', '深圳', '杭州', '南京', '石家莊', '銀川']) stations = {} stations['kone'] = set(['北京', '上海', '廣州']) stations['ktwo'] = set(['北京''杭州', '南京']) stations['kthree'] = set(['廣州', '深圳', '杭州']) stations['kfour'] = set(['北京', '銀川']) stations['kfive'] = set(['石家莊', '銀川']) 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)