What
A greedy algorithm is an algorithmic paradigm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
說白了,貪心算法是分步走,每一個找到最優解。總體的找到解不一定是最優解。
Why
Compare to Dynamic Programming
- A greedy algorithm is effective powerful, beacuse it isn't pay attention to global result.
- More then appropriate
NP
(Non-determine Problem) 問題
How to design
- 貪心算法使用組合優化問題,該問題滿足優化原則
- 求解過程是多步判斷過程,最終的判斷序列對應問題的最優解
- 判斷一句某種
短視的
貪心選擇原則,原則的好壞決定了算法的成敗 - 貪心法必須進行正確性證明
Greedy Select
input : S=set{1,2 ... n},活動開始時間Si,截止時間Fi
output : A, it is one of S
A = {1}
j = 1
for i =2 to n do
if Si > Fj
then A = A + {i}
j = i
return A
Sample
- Generate Minimum Tree
Prim
input : Graphic G = < Vector, Edge, Weight>
output : Tree T
S = {1} // start
T = null
while V - S != null do
temp = V - S
j = selectMinimalWeightOfEdge(temp)
T = T + ei
S = S + j
Kruskal
input : Graphic G = < Vector, Edge, Weight>
output : Tree T
1. Sorting edges by Weight
2. T = null
3. repeat
4. e = Minimal edge
5. if e is not into continue branch T
6. then T = T + e
7. E = E - e
8. Until T include n-1 edge