
贪心算法:
1.确定问题最优子结构
2.设计递归算法
3.证明贪心算法安全性
4.将递归转换为迭代
自己解答:
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort()
s.sort()
j = res = 0
for index in range(len(g)):
while(j < len(s)):
if g[index] <= s[j]:
res += 1
j += 1
break
else:
j += 1
return res
优秀解答:
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort()
s.sort()
index = 0
count = 0
for i in s:
if g[index] <= i:
count += 1
index += 1
if index == len(g):
break
return count
本文介绍了一种使用贪心算法解决分配问题的方法,并提供了两种Python实现方案。通过将儿童贪婪程度和饼干大小排序后进行匹配,实现了最大化满足条件的解决方案。
534

被折叠的 条评论
为什么被折叠?



