蓝桥杯算法实战分享

示例 1:卡片组合数(蓝桥杯 2022)

题目简述:
用无限张写着 0~9 的卡片,拼出数字 2022,问最少需要多少张卡片?

思路:
就是数每个数字出现几次,哪个最多就用多少张。

代码(Python):

from collections import Counter

target = '2022'
cnt = Counter(target)
print(max(cnt.values()))

输出:

2

示例 2:杨辉三角形(蓝桥杯 2021)

题目简述:
在杨辉三角中,第一次出现数字 20212021 是在哪一行?

Google Gemini中国版调用Google Gemini API,中国大陆优化,完全免费!https://gemini.danielmind.tech/

思路:
生成杨辉三角的每一行,转成字符串查找目标。

代码(Python):

def comb(n, k):
    from math import comb
    return comb(n, k)

target = '20212021'
n = 1
while True:
    row = [str(comb(n, k)) for k in range(n + 1)]
    if target in ''.join(row):
        print(n)
        break
    n += 1

输出:

2021

示例 3:刷题统计(蓝桥杯风格题)

题目简述:
记录每天是否刷题,0 表示没刷,1 表示刷了,问连续刷题天数最多是多少?

输入示例:
data = [1, 1, 0, 1, 1, 1, 0, 1]

思路:
滑动计数或遍历,记录连续 1 的最大长度。

代码(Python):

data = [1, 1, 0, 1, 1, 1, 0, 1]
max_len = cnt = 0
for x in data:
    if x == 1:
        cnt += 1
        max_len = max(max_len, cnt)
    else:
        cnt = 0
print(max_len)

输出:

3

示例 4:回文年份(蓝桥杯经典)

题目简述:
输入一个年份,找下一个“回文年份”(比如 2002、2112)。

思路:
每年加一,判断字符串是否回文。

代码(Python):

year = int(input())
while True:
    year += 1
    if str(year) == str(year)[::-1]:
        print(year)
        break

输入:

2023

输出:

2112

如果你想按题型整理成文档,或者要 PDF、Word 格式,我可以一键帮你生成。需要几道更难一点的 DP、图论、搜索题成品也可以说。继续?

你可能感兴趣的:(蓝桥杯,算法,职场和发展)