贪婪算法简介
贪婪算法(Greedy Algorithm)是一种在每一步选择中都采取当前状态下最好或最优(即最有利)的选择,从而希望导致结果是全局最好或最优的算法。贪婪算法通常用于解决优化问题,如最小化成本、最大化收益等。它并不保证得到最优解,但在很多问题中,它能产生很好的近似解或最优解。
贪婪算法的关键在于贪心选择性质:每一步所做的选择都是当前状态下的最优选择,并且这种选择不会依赖于子问题的解。
示例问题:找零钱问题
假设一个商店只销售价格为整数元的商品,并且只接受整数元的货币。给定一个商品的价格n
元和一个无限数量的货币单位[1,2,5,10,20,50,100]
(分别代表1元、2元、5元、10元、20元、50元和100元),编写一个程序计算找零给顾客的最少货币数量。
C# 实现
using System;
using System.Collections.Generic;
class GreedyChangeMaker
{
static List<int> denominations = new List<int> { 100, 50, 20, 10, 5, 2, 1 };
static int MakeChange(int amount)
{
int count = 0;
for (int i = 0; i < denominations.Count; i++)
{
while (amount >= denominations[i])
{
amount -= denominations[i];
count++;
}
}
return count;
}
static void Main()
{
int amount = 63;
Console.WriteLine($"Minimum number of coins required: {MakeChange(amount)}");
}
}
C++ 实现
#include <iostream>
#include <vector>
using namespace std;
int makeChange(int amount) {
vector<int> denominations = {100, 50, 20, 10, 5, 2, 1};
int count = 0;
for (int coin : denominations) {
while (amount >= coin) {
amount -= coin;
count++;
}
}
return count;
}
int main() {
int amount = 63;
cout << "Minimum number of coins required: " << makeChange(amount) << endl;
return 0;
}
Python 实现
def make_change(amount):
denominations = [100, 50, 20, 10, 5, 2, 1]
count = 0
for coin in denominations:
count += amount // coin
amount %= coin
return count
amount = 63
print(f"Minimum number of coins required: {make_change(amount)}")
Java 实现
public class GreedyChangeMaker {
private static final int[] denominations = {100, 50, 20, 10, 5, 2, 1};
public static int makeChange(int amount) {
int count = 0;
for (int denomination : denominations) {
while (amount >= denomination) {
amount -= denomination;
count++;
}
}
return count;
}
public static void main(String[] args) {
int amount = 63;
System.out.println("Minimum number of coins required: " + makeChange(amount));
}
}