Skip to Content
🧮 CTDL & Giải thuật🎯 Thuật toán tham lam

Thuật toán tham lam (Greedy Algorithm)

Greedy là gì?

Greedy Algorithm chọn phương án tốt nhất tại thời điểm hiện tại với hy vọng dẫn đến nghiệm tối ưu toàn cục.

⚠️

Greedy không phải lúc nào cũng cho nghiệm tối ưu! Cần chứng minh tính đúng đắn.

Activity Selection

def activity_selection(activities): """Chọn nhiều hoạt động nhất không chồng chéo""" activities.sort(key=lambda x: x[1]) # Sort by end time result = [activities[0]] last_end = activities[0][1] for start, end in activities[1:]: if start >= last_end: result.append((start, end)) last_end = end return result

Fractional Knapsack

def fractional_knapsack(items, capacity): """items = [(weight, value), ...]""" # Sort by value/weight ratio items.sort(key=lambda x: x[1] / x[0], reverse=True) total_value = 0 for weight, value in items: if capacity >= weight: capacity -= weight total_value += value else: total_value += value * (capacity / weight) break return total_value

Greedy vs Dynamic Programming

GreedyDP
Quyết địnhMột lần, không quay lạiXem xét tất cả
Độ phức tạpThường O(n log n)Thường O(n²)
Tính đúng đắnCần chứng minhLuôn đúng

Tiếp theo: Quay lui (Backtracking)

Last updated on