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))