1. 面试题57 - II. 和为s的连续正数序列
题目描述
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
1 <= target <= 10^5
解答
滑动窗口解法,具体看参考链接:
https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/shi-yao-shi-hua-dong-chuang-kou-yi-ji-ru-he-yong-h/
class Solution:
def findContinuousSequence(self, target: int) -> List[List[int]]:
left = 1
right = 1
total = 0
res = []
while left <= target // 2:
if total < target:
total += right
right += 1
elif total > target:
total -= left
left += 1
else:
temp = []
for i in range(left, right):
temp.append(i)
res.append(temp)
total -= left
left += 1
return res
2. 解数独
题目描述
编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 ‘.’ 表示。
解答
通用思路
- 可用的数放在一个数组里,便于取数;
- 需要填的位置放在另一个数组里, 需要填的数组为空时,循环结束。
参考:
https://leetcode-cn.com/problems/sudoku-solver/solution/pythonsethui-su-chao-guo-95-by-mai-mai-mai-mai-zi/
3. 面试题10- I. 斐波那契数列
题目描述
解答
重点是: 解除最大递归数的装饰器
from functools import lru_cache
class Solution:
@lru_cache(None)
def fib(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return int((self.fib(n-1) + self.fib(n-2)) % (1e9+7))