455. Assign Cookies -- 贪心算法

来源:互联网 发布:xp网络共享打印机设置 编辑:程序博客网 时间:2024/05/16 11:43

455. Assign Cookies – 贪心算法

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.Note:You may assume the greed factor is always positive. You cannot assign more than one cookie to one child.Example 1:Input: [1,2,3], [1,1]Output: 1Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.You need to output 1.Example 2:Input: [1,2], [1,2,3]Output: 2Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2.

解1:
题目就给出了这道题目的考点,greed factor gi,可以看出考的是贪心算法,但是如果题目不这么描述呢?从哪里可以看出这是一道贪心算法题?
现在我只能从现在做的题目中提取出贪心算法的一种模式:分配,并且只要一个。

从列表的尾部开始判断。

这里孩子的列表中的值只用一次然后扔掉,饼干的值要多次和孩子的值比较,所以用一个数记录饼干列表的索引,当饼干被分配了以后,指针就指向前一个,这就是贪心吧。

class Solution(object):    def findContentChildren(self, g, s):        """        :type g: List[int]        :type s: List[int]        :rtype: int        """        s.sort()        g.sort()        count = 0        s_len = len(s)        while len(g) and s_len:            child = g.pop()            if child <= s[s_len - 1]:                count += 1                s_len -= 1        return count

解2:
从列表的前面开始判断。

class Solution(object):    def findContentChildren(self, g, s):        """        :type g: List[int]        :type s: List[int]        :rtype: int        """        g.sort()        s.sort()        childi = 0        cookiei = 0        while cookiei < len(s) and childi < len(g):            if s[cookiei] > g[childi]:                child += 1            cookiei += 1        return childi

贪心算法

贪心算法的定义:

贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,只做出在某种意义上的局部最优解。贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。
解题的一般步骤是:

1.建立数学模型来描述问题;
2.把求解的问题分成若干个子问题;
3.对每一子问题求解,得到子问题的局部最优解;
4.把子问题的局部最优解合成原来问题的一个解。

0 0
原创粉丝点击