8000 第四周作业 by lglove · Pull Request #917 · algorithm001/algorithm · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

第四周作业 #917

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Week_04/id_24/NOTE.md
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
# 学习笔记
# 学习笔记

[最小花费爬楼问题](https://leetcode-cn.com/problems/min-cost-climbing-stairs/submissions)

该问题属于简单问题,处理难点在于理解题目,找出递推公式,首先题目的表述会给我们理解题目造成一定的误解,数组给的是每一层消耗的体力而不是
每一步的花费,我们需要自己计算到达该楼层花费的总体力,然后每一步的选择有两种,走一步还是走两步,到达该层的最小花费就是到达前一层和前二层花费的最小值,由此我们得出递推公式 f(n) = min(f(n-1)+cost(n-1), f(n-2)+cost(n-2)),然后就是代码实现,需要注意的是边界条件。


[分发饼干](https://leetcode-cn.com/problems/assign-cookies/)

该问题属于比较经典的贪心算法,首先我们应该认识到贪心算法的局限性,贪心算法因为每一次操作都取得是每次操作花费最小的方案,这样做有一个问题就是无法兼顾到全局,当前最优解不一定是全局最优解。
接下来,我们这道题里面分发饼干的案例属于比较经典的贪心算法解法,为了让尽可能多的满足更多孩子的需求,我们总是优先用最小的饼干满足需求最低的孩子,能够做到最大限度的利用饼干。

第一步我们要处理的是需要把饼干和孩子的需求都进行排序,然后以饼干来遍历,依次找最满足需求的孩子,然后需要注意的是如果饼干已经分配我们需要从我们的数组里减去该饼干,从孩子里减去已经分配饼干的孩子。
24 changes: 24 additions & 0 deletions Week_04/id_24/leetcode_455_024.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[455. 分发饼干](https://leetcode-cn.com/problems/assign-cookies/submissions/)

###解题思路:看到这个题首先想到的就是贪心算法,贪心算法实现上需要注意两个问题,
###1. 饼干的大小和孩子的期望需要排序
###2. 需要及时跳过已经分配的饼干,不允许饼干的多次分配

def find_content_children(g, s)
i = 0
j = 0
child = 0
s = s.sort
g = g.sort

while i < s.length && j < g.length
if s[i] >= g[j]
i+=1
j+=1
child += 1
else
i+=1
end
end
return child
end
18 changes: 18 additions & 0 deletions Week_04/id_24/leetcode_746_024.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[746: 最小花费爬楼梯](https://leetcode-cn.com/problems/min-cost-climbing-stairs/submissions/)

###解题思路 动态规划问题,主要还是要找到递推公式
### 由题目我们能到看到到达当前位置的最小花费来自于上一步和上上一步的最小花费
### 递归公式就是 f(n) = min(f(n-1) + cost[n-1], f(n-2) + cost(n-2)), f(0) = 0, f[1] = 0,
### f[2] = min(f(1) + cost[1], f(0)+cost[0])

def min_cost_climbing_stairs(cost)
f = []
f[0] = 0
f[1] = 0
f[2] = [f[0] + cost[0], f[1]+cost[1]].min
for i in (2..cost.length) do
f[i] = [f[i-2] + cost[i-2], f[i-1]+cost[i-1]].min
end
return f[cost.length]

end
0