贪心算法
1.关于饼干分配
问题:输入: g = [1,2,3], s = [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。
分析:
首先对数组 g和s排序,然后从小到大遍历 g 中的每个元素,对于每个元素找到能满足该元素的 ss 中的最小的元素。具体而言,令 i 是 g的下标,jj是 s 的下标,初始时 i 和 j 都为 0,进行如下操作。
对于每个元素 g[i],找到未被使用的最小的 j使得 g[i]<=s[j],则 s[j]可以满足 g[i]。由于g和s已经排好序,因此整个过程只需要对数组g和s各遍历一次。当两个数组之一遍历结束时,说明所有的孩子都被分配到了饼干,或者所有的饼干都已经被分配或被尝试分配(可能有些饼干无法分配给任何孩子),此时被分配到饼干的孩子数量即为可以满足的最多数量。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int numOfChildren = g.size(), numOfCookies = s.size();
int count = 0;
for (int i = 0, j = 0; i < numOfChildren && j < numOfCookies; i++, j++) {
while (j < numOfCookies && g[i] > s[j]) {
j++; //其实就是排序后按照最小要求取值
}
if (j < numOfCookies) {
count++;
}
}
return count;
}
};
2.关于钱币找零
问题:钱币找零问题:这个问题在我们的日常生活中很普遍。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。在程序中已经事先将Value按照从小到大的顺序排好。
贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择,首先肯定是使用面值最大的钱,比如总共要130元,则第一步肯定是选择100元面值的,第二步选择20元面值的,第三步选择10元面值的。
#include <iostream>
#include <math.h>
using namespace std;
//当前的钱库,面值以及对应数量
int single_money[7] = {1,2,5,10,20,50,100};
int number_money[7] = {2,5,0,3,4,0,4};
//每种面值使用贪心算法后需要使用的张数
int count[7] = {};
int total_count;
int tanxin(int money)
{
if (money >= 0) //考虑一下输入规范的问题
{
for (int i = 6; i >= 0; i--) //倒寻,从面值最大的先寻找
{
count[i] = min(number_money[i],money/single_money[i]); //比较现存张数以及需要多少张
money = money - count[i]*single_money[i];
}
return 0;
}
else
{
return money;
}
}
int main(int argc,char** argv)
{
int money;
cout<<"Please input the amount of money:";
cin>>money;
if(! tanxin(money)) //if里的函数运行
{
cout<<"100元:"<<count[6]<<"张"<<endl; //输出
cout<<"50元:"<<count[5]<<"张"<<endl;
cout<<"20元:"<<count[4]<<"张"<<endl;
cout<<"10元:"<<count[3]<<"张"<<endl;
cout<<"5元:"<<count[2]<<"张"<<endl;
cout<<"2元:"<<count[1]<<"张"<<endl;
cout<<"1元:"<<count[0]<<"张"<<endl;
}
else
{
cout<<"Ops, Wrong number~";
}
system("pause");
return 0;
}
转载:https://leetcode-cn.com/leetbook/read/greedy/rvrk1c/
原文链接:https://blog.csdn.net/misayaaaaa/article/details/72789998

浙公网安备 33010602011771号