算法題筆記——滑動窗口、數獨

面試題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

解數獨

題目描述

編寫一個程序,通過已填充的空格來解決數獨問題。

一個數獨的解法需遵循如下規則:

數字 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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章