[Python] 贪心算法简单版

贪心算法-简单版

贪心算法的一般使用场景是给定一个列表ls, 让你在使用最少的数据的情况下达到或超过n .

我们就来使用上面讲到的这个朴素的例题来讲讲贪心算法的基本模板:

2-1.排序

既然要用最少的数据, 我们就要优先用大的数据拼 , 为了实现这个效果, 我们得先给列表从大到小排序.

python 复制代码
sorted(ls, reverse = True)
# 别忘了reverse = True从大到小

2-2.选择

我们需要遍历列表, 每次选出现在的元素, 记录当前总和和累加次数, 当总和大于等于n时, 结束循环.

python 复制代码
tot = 0
cnt = 0
# 注意一个很容易错的地方, 这里的语句顺序不可改变!
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

2-3.完整简单版模板

注释版:

python 复制代码
# 输入
n = int(input())
ls = [int(i) for i in input().split()]

# 排序
sorted(ls, reverse = True)

# 主要算法, 摘大苹果
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

记忆版:

python 复制代码
n = int(input())
ls = [int(i) for i in input().split()]
sorted(ls, reverse = True)
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1
相关推荐
灰太狼大王灬19 分钟前
Go 项目从开发到部署笔记
开发语言·笔记·golang
小树懒(-_-)21 分钟前
SEO:Java项
java·开发语言
许泽宇的技术分享29 分钟前
Ansible核心架构深度剖析:从源码看IT自动化的“简单“哲学
python·ansible·自动化运维·devops·it基础设施
风遥~1 小时前
快速了解并使用Matplotlib库
人工智能·python·数据分析·matplotlib
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 63: 图像渲染、岛屿数量
java·数据结构·算法·leetcode·决策树·贪心算法·深度优先
databook1 小时前
Manim实现旋转扭曲特效
后端·python·动效
胖咕噜的稞达鸭1 小时前
二叉树进阶面试题:最小栈 栈的压入·弹出序列 二叉树层序遍历
开发语言·c++
wzg20161 小时前
pyqt5 简易入门教程
开发语言·数据库·qt
心静财富之门2 小时前
【无标题】标签单击事件
开发语言·php
草莓熊Lotso2 小时前
揭开 C++ vector 底层面纱:从三指针模型到手写完整实现
开发语言·c++