From 7214c83980616b6d5ca9b3a441bf599495b7d066 Mon Sep 17 00:00:00 2001 From: huanghaifeng Date: Sun, 30 Jun 2019 21:26:17 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8=E4=BD=9C=E4=B8=9A#0?= =?UTF-8?q?26?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Week_04/id_26/LeetCode_169_26.py | 78 ++++++++++++++++ Week_04/id_26/LeetCode_208_26.py | 101 +++++++++++++++++++++ Week_04/id_26/LeetCode_211_26.py | 89 ++++++++++++++++++ Week_04/id_26/LeetCode_240_26.py | 69 ++++++++++++++ Week_04/id_26/LeetCode_46_26.py | 54 +++++++++++ Week_04/id_26/LeetCode_51_26.py | 96 ++++++++++++++++++++ Week_04/id_26/LeetCode_53_26.py | 56 ++++++++++++ Week_04/id_26/LeetCode_70_26.py | 72 +++++++++++++++ Week_04/id_26/LeetCode_720_26.py | 151 +++++++++++++++++++++++++++++++ Week_04/id_26/LeetCode_77_26.py | 53 +++++++++++ Week_04/id_26/LeetCode_784_26.py | 62 +++++++++++++ Week_04/id_26/LeetCode_78_26.py | 57 ++++++++++++ 12 files changed, 938 insertions(+) create mode 100644 Week_04/id_26/LeetCode_169_26.py create mode 100644 Week_04/id_26/LeetCode_208_26.py create mode 100644 Week_04/id_26/LeetCode_211_26.py create mode 100644 Week_04/id_26/LeetCode_240_26.py create mode 100644 Week_04/id_26/LeetCode_46_26.py create mode 100644 Week_04/id_26/LeetCode_51_26.py create mode 100644 Week_04/id_26/LeetCode_53_26.py create mode 100644 Week_04/id_26/LeetCode_70_26.py create mode 100644 Week_04/id_26/LeetCode_720_26.py create mode 100644 Week_04/id_26/LeetCode_77_26.py create mode 100644 Week_04/id_26/LeetCode_784_26.py create mode 100644 Week_04/id_26/LeetCode_78_26.py diff --git a/Week_04/id_26/LeetCode_169_26.py b/Week_04/id_26/LeetCode_169_26.py new file mode 100644 index 00000000..c54a30c6 --- /dev/null +++ b/Week_04/id_26/LeetCode_169_26.py @@ -0,0 +1,78 @@ +# +# @lc app=leetcode.cn id=169 lang=python +# +# [169] 求众数 +# +# https://leetcode-cn.com/problems/majority-element/description/ +# +# algorithms +# Easy (59.48%) +# Likes: 261 +# Dislikes: 0 +# Total Accepted: 49.3K +# Total Submissions: 82.6K +# Testcase Example: '[3,2,3]' +# +# 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 +# +# 你可以假设数组是非空的,并且给定的数组总是存在众数。 +# +# 示例 1: +# +# 输入: [3,2,3] +# 输出: 3 +# +# 示例 2: +# +# 输入: [2,2,1,1,1,2,2] +# 输出: 2 +# +# +# + + +class Solution(object): + def majorityElement1(self, nums): + """ + :type nums: List[int] + :rtype: int + 解法1:排序 + """ + nums.sort() + return nums[len(nums)//2] + + def majorityElement(self, nums): + """ + :type nums: List[int] + :rtype: int + 解法2: 递归+分治 + 分治问题模板步骤: + 1.结束条件 + 2.拆分子问题 + 3.递归处理子问题 + 4.处理子问题的结果 + """ + def helper(left, right): + + if left == right: + return nums[left] + + mid = (right+left) // 2 + + leftNum = helper(left, mid) + rightNum = helper(mid+1, right) + + if leftNum == rightNum: + return leftNum + leftCount, rightCount = 0, 0 + for i in range(left, right+1): + if nums[i] == leftNum: + leftCount += 1 + elif nums[i] == rightNum: + rightCount += 1 + return leftNum if leftCount >= rightCount else rightNum + + return helper(0, len(nums)-1) + + +# print(Solution().majorityElement([1, 2, 1, 3, 1, 2, 1])) diff --git a/Week_04/id_26/LeetCode_208_26.py b/Week_04/id_26/LeetCode_208_26.py new file mode 100644 index 00000000..b1765ecb --- /dev/null +++ b/Week_04/id_26/LeetCode_208_26.py @@ -0,0 +1,101 @@ +# +# @lc app=leetcode.cn id=208 lang=python +# +# [208] 实现 Trie (前缀树) +# +# https://leetcode-cn.com/problems/implement-trie-prefix-tree/description/ +# +# algorithms +# Medium (58.88%) +# Likes: 77 +# Dislikes: 0 +# Total Accepted: 8K +# Total Submissions: 13.5K +# Testcase Example: '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]' +# +# 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 +# +# 示例: +# +# Trie trie = new Trie(); +# +# trie.insert("apple"); +# trie.search("apple"); // 返回 true +# trie.search("app"); // 返回 false +# trie.startsWith("app"); // 返回 true +# trie.insert("app"); +# trie.search("app"); // 返回 true +# +# 说明: +# +# +# 你可以假设所有的输入都是由小写字母 a-z 构成的。 +# 保证所有输入均为非空字符串。 +# +# +# + + +class TireNode(object): + def __init__(self): + self.children = {} + self.end = False + + +class Trie(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.root = TireNode() + + def insert(self, word): + """ + Inserts a word into the trie. + :type word: str + :rtype: None + """ + node = self.root + for c in word: + if c not in node.children: + node.children[c] = TireNode() + node = node.children[c] + node.end = True + + def search(self, word): + """ + Returns if the word is in the trie. + :type word: str + :rtype: bool + """ + node = self.root + for c in word: + if c not in node.children: + return False + node = node.children[c] + return node.end + + def startsWith(self, prefix): + """ + Returns if there is any word in the trie that starts with the given prefix. + :type prefix: str + :rtype: bool + """ + node = self.root + for c in prefix: + if c not in node.children: + return False + node = node.children[c] + return True + + +# Your Trie object will be instantiated and called as such: +# trie = Trie() +# print(trie.insert("apple")) +# print(trie.search("apple")) +# print(trie.search("app")) +# print(trie.startsWith("app")) +# print(trie.insert("app")) +# print(trie.search("app")) + diff --git a/Week_04/id_26/LeetCode_211_26.py b/Week_04/id_26/LeetCode_211_26.py new file mode 100644 index 00000000..4166d498 --- /dev/null +++ b/Week_04/id_26/LeetCode_211_26.py @@ -0,0 +1,89 @@ +# +# @lc app=leetcode.cn id=211 lang=python +# +# [211] 添加与搜索单词 - 数据结构设计 +# +# https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/description/ +# +# algorithms +# Medium (38.92%) +# Likes: 51 +# Dislikes: 0 +# Total Accepted: 2.8K +# Total Submissions: 7.3K +# Testcase Example: '["WordDictionary","addWord","addWord","addWord","search","search","search","search"]\n[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]' +# +# 设计一个支持以下两种操作的数据结构: +# +# void addWord(word) +# bool search(word) +# +# +# search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。 +# +# 示例: +# +# addWord("bad") +# addWord("dad") +# addWord("mad") +# search("pad") -> false +# search("bad") -> true +# search(".ad") -> true +# search("b..") -> true +# +# +# 说明: +# +# 你可以假设所有单词都是由小写字母 a-z 组成的。 +# +# + + +class TrieNode(object): + def __init__(self): + self.children = {} + self.end = False + + +class WordDictionary(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.root = TrieNode() + + def addWord(self, word): + """ + Adds a word into the data structure. + :type word: str + :rtype: None + """ + node = self.root + for c in word: + if c not in node.children: + node.children[c] = TrieNode() + node = node.children[c] + node.end = True + + def search(self, word): + """ + Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. + :type word: str + :rtype: bool + """ + self.ans = False + self._match(self.root, word) + return self.ans + + def _match(self, root, word): + if not word: + if root.end: + self.ans = root.end + return + if word[0] == '.': + for node in root.children.values(): + self._match(node, word[1:]) + if word[0] not in root.children: + return + self._match(root.children[word[0]], word[1:]) diff --git a/Week_04/id_26/LeetCode_240_26.py b/Week_04/id_26/LeetCode_240_26.py new file mode 100644 index 00000000..9426a00a --- /dev/null +++ b/Week_04/id_26/LeetCode_240_26.py @@ -0,0 +1,69 @@ +# +# @lc app=leetcode.cn id=240 lang=python +# +# [240] 搜索二维矩阵 II +# +# https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/ +# +# algorithms +# Medium (36.82%) +# Likes: 111 +# Dislikes: 0 +# Total Accepted: 17.8K +# Total Submissions: 48.2K +# Testcase Example: '[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]\n5' +# +# 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: +# +# +# 每行的元素从左到右升序排列。 +# 每列的元素从上到下升序排列。 +# +# +# 示例: +# +# 现有矩阵 matrix 如下: +# +# [ +# ⁠ [1, 4, 7, 11, 15], +# ⁠ [2, 5, 8, 12, 19], +# ⁠ [3, 6, 9, 16, 22], +# ⁠ [10, 13, 14, 17, 24], +# ⁠ [18, 21, 23, 26, 30] +# ] +# +# +# 给定 target = 5,返回 true。 +# +# 给定 target = 20,返回 false。 +# +# + + +class Solution(object): + def searchMatrix(self, matrix, target): + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + 思路:从左下角开始,相等直接返回 + 若大于目标值,则不可能在这一列,指针向左 + 若小于目标值,则不可能在这一排,指针向上 + 时间复杂度O(m+n) + """ + if not matrix or not matrix[0]: + return False + m, n = len(matrix)-1, 0 + + while m >= 0 and n < len(matrix[0]): + if matrix[m][n] == target: + return True + if matrix[m][n] < target: + n += 1 + else: + m -= 1 + return False + + +# print(Solution().searchMatrix([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [ + # 3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 333)) diff --git a/Week_04/id_26/LeetCode_46_26.py b/Week_04/id_26/LeetCode_46_26.py new file mode 100644 index 00000000..73b4df32 --- /dev/null +++ b/Week_04/id_26/LeetCode_46_26.py @@ -0,0 +1,54 @@ +# +# @lc app=leetcode.cn id=46 lang=python +# +# [46] 全排列 +# +# https://leetcode-cn.com/problems/permutations/description/ +# +# algorithms +# Medium (69.33%) +# Likes: 291 +# Dislikes: 0 +# Total Accepted: 28.6K +# Total Submissions: 41.1K +# Testcase Example: '[1,2,3]' +# +# 给定一个没有重复数字的序列,返回其所有可能的全排列。 +# +# 示例: +# +# 输入: [1,2,3] +# 输出: +# [ +# ⁠ [1,2,3], +# ⁠ [1,3,2], +# ⁠ [2,1,3], +# ⁠ [2,3,1], +# ⁠ [3,1,2], +# ⁠ [3,2,1] +# ] +# +# + + +class Solution(object): + def permute(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + 时间复杂度:O(n^2) + """ + ans = [] + n = len(nums) + + def helper(path=[], invited=set()): + if len(path) == n: + return ans.append(path) + for j in nums: + if j not in invited: + invited.add(j) + helper(path+[j], invited) + invited.remove(j) + + helper() + return ans diff --git a/Week_04/id_26/LeetCode_51_26.py b/Week_04/id_26/LeetCode_51_26.py new file mode 100644 index 00000000..45652f1a --- /dev/null +++ b/Week_04/id_26/LeetCode_51_26.py @@ -0,0 +1,96 @@ +# +# @lc app=leetcode.cn id=51 lang=python +# +# [51] N皇后 +# +# https://leetcode-cn.com/problems/n-queens/description/ +# +# algorithms +# Hard (62.79%) +# Likes: 181 +# Dislikes: 0 +# Total Accepted: 9K +# Total Submissions: 14.2K +# Testcase Example: '4' +# +# n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 +# +# +# +# 上图为 8 皇后问题的一种解法。 +# +# 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 +# +# 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。 +# +# 示例: +# +# 输入: 4 +# 输出: [ +# ⁠[".Q..", // 解法 1 +# ⁠ "...Q", +# ⁠ "Q...", +# ⁠ "..Q."], +# +# ⁠["..Q.", // 解法 2 +# ⁠ "Q...", +# ⁠ "...Q", +# ⁠ ".Q.."] +# ] +# 解释: 4 皇后问题存在两个不同的解法。 +# +# +# + + +class Solution(object): + + def solveNQueens1(self, n): + """ + :type n: int + :rtype: List[List[str]] + 解法1:深度遍历,用set记录和、差、列 + """ + ans = [] + + def dfs(i, col=set(), add=set(), minus=set(), grid=[]): + if i == n: + return ans.append(grid) + for j in range(n): + if j not in col and i + j not in add and i - j not in minus: + col.add(j) + add.add(i+j) + minus.add(i-j) + line = ''.join(['Q' if m == j else '.' for m in range(n)]) + dfs(i+1, col, add, minus, grid + [line]) + col.remove(j) + add.remove(i+j) + minus.remove(i-j) + dfs(0) + return ans + + def solveNQueens(self, n): + """ + :type n: int + :rtype: List[List[str]] + 解法2:深度遍历,用位记录和、差、列 + """ + ans = [] + + def dfs(pos=[], row=0, col=0, pie=0, na=0): + if row == n: + ans.append(pos) + return + bits = ~(col | pie | na) & ((1 << n) - 1) + while bits > 0: + p = bits & -bits + line = ''.join(['Q' if p >> i & 1 else '.' for i in range(n)]) + dfs(pos + [line], row + 1, col | p, + (pie | p) << 1, (na | p) >> 1) + bits &= bits - 1 + + dfs() + return ans + + +print(Solution().solveNQueens(4)) diff --git a/Week_04/id_26/LeetCode_53_26.py b/Week_04/id_26/LeetCode_53_26.py new file mode 100644 index 00000000..8e8c8391 --- /dev/null +++ b/Week_04/id_26/LeetCode_53_26.py @@ -0,0 +1,56 @@ +# +# @lc app=leetcode.cn id=53 lang=python +# +# [53] 最大子序和 +# +# https://leetcode-cn.com/problems/maximum-subarray/description/ +# +# algorithms +# Easy (45.36%) +# Likes: 995 +# Dislikes: 0 +# Total Accepted: 64.5K +# Total Submissions: 141.4K +# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' +# +# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 +# +# 示例: +# +# 输入: [-2,1,-3,4,-1,2,1,-5,4], +# 输出: 6 +# 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 +# +# +# 进阶: +# +# 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 +# +# + + +class Solution(object): + def maxSubArray1(self, nums): + """ + :type nums: List[int] + :rtype: int + 解法1:动态规划,dp[i]表示包含i的最大连续子数组和 + """ + dp = [i for i in nums] + for i in range(1, len(nums)): + dp[i] = max(dp[i-1], 0) + nums[i] + return max(dp) + + def maxSubArray(self, nums): + """ + 解法2:跟动态规划的思路类似,只需要记录包含当前节点的最大子数组和 + """ + ret, _max = nums[0], nums[0] + for i in range(1, len(nums)): + _max = max(_max, 0) + nums[i] + ret = max(ret, _max) + return ret + + +print(Solution().maxSubArray1([1])) +print(Solution().maxSubArray1([-2, 1, -3, 4, -1, 2, 1, -5, 4])) diff --git a/Week_04/id_26/LeetCode_70_26.py b/Week_04/id_26/LeetCode_70_26.py new file mode 100644 index 00000000..71457fb8 --- /dev/null +++ b/Week_04/id_26/LeetCode_70_26.py @@ -0,0 +1,72 @@ +# +# @lc app=leetcode.cn id=70 lang=python +# +# [70] 爬楼梯 +# +# https://leetcode-cn.com/problems/climbing-stairs/description/ +# +# algorithms +# Easy (45.50%) +# Likes: 513 +# Dislikes: 0 +# Total Accepted: 54.7K +# Total Submissions: 119.8K +# Testcase Example: '2' +# +# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 +# +# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? +# +# 注意:给定 n 是一个正整数。 +# +# 示例 1: +# +# 输入: 2 +# 输出: 2 +# 解释: 有两种方法可以爬到楼顶。 +# 1. 1 阶 + 1 阶 +# 2. 2 阶 +# +# 示例 2: +# +# 输入: 3 +# 输出: 3 +# 解释: 有三种方法可以爬到楼顶。 +# 1. 1 阶 + 1 阶 + 1 阶 +# 2. 1 阶 + 2 阶 +# 3. 2 阶 + 1 阶 +# +# +# + + +class Solution(object): + def climbStairs1(self, n): + """ + :type n: int + :rtype: int + """ + if not n: + return n + dp = [0] * (n+1) + dp[0] = dp[1] = 1 + for i in range(2, n+1): + dp[i] = dp[i-1]+dp[i-2] + return dp[n] + + def climbStairs2(self, n): + """ + :type n: int + :rtype: int + """ + if not n: + return n + a, b = 1, 1 + for i in range(2, n+1): + b, a = a + b, b + return b + + +# print(Solution().climbStairs2(1)) +# print(Solution().climbStairs2(3)) +# print(Solution().climbStairs2(4)) diff --git a/Week_04/id_26/LeetCode_720_26.py b/Week_04/id_26/LeetCode_720_26.py new file mode 100644 index 00000000..e25c4487 --- /dev/null +++ b/Week_04/id_26/LeetCode_720_26.py @@ -0,0 +1,151 @@ +#!/usr/bin/python +# -*- coding: UTF-8 -*- +# @lc app=leetcode.cn id=720 lang=python +# +# [720] 词典中最长的单词 +# +# https://leetcode-cn.com/problems/longest-word-in-dictionary/description/ +# +# algorithms +# Easy (42.52%) +# Likes: 36 +# Dislikes: 0 +# Total Accepted: 2.7K +# Total Submissions: 6.3K +# Testcase Example: '["w","wo","wor","worl","world"]' +# +# +# 给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。 +# +# 若无答案,则返回空字符串。 +# +# 示例 1: +# +# +# 输入: +# words = ["w","wo","wor","worl", "world"] +# 输出: "world" +# 解释: +# 单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。 +# +# +# 示例 2: +# +# +# 输入: +# words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] +# 输出: "apple" +# 解释: +# "apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。 +# +# +# 注意: +# +# +# 所有输入的字符串都只包含小写字母。 +# words数组长度范围为[1,1000]。 +# words[i]的长度范围为[1,30]。 +# +# +# + + +import collections + + +class Solution(object): + def longestWord1(self, words): + """ + :type words: List[str] + :rtype: str + 解法1: 先排序,后面的单词去掉最后一个字母在前面出现过则添加入集合,找出最长的即可,相同长度取前面的 + """ + words.sort() + visited, ans = set(), '' + for word in words: + if len(word) == 1 or word[:-1] in visited: + visited.add(word) + if len(ans) < len(word): + ans = word + return ans + + def longestWord(self, words): + """ + :type words: List[str] + :rtype: str + 解法2: 字典树 + 使用两种不同的遍历方式 + """ + trie = Trie() + for word in words: + trie.insert(word) + # return trie.longest2() + return trie.longest1() + + +class TrieNode: + def __init__(self): + self.children = {} + self.word = '' + self.end = False + + +class Trie: + def __init__(self): + self.root = TrieNode() + + def insert(self, word): + node = self.root + for c in word: + if c not in node.children: + node.children[c] = TrieNode() + node = node.children[c] + node.end = True + node.word = word + + def longest1(self): + import collections + queue = collections.deque([self.root]) + ans = '' + + while queue: + node = queue.pop() + for c, n in node.children.items(): + if n.end: + queue.append(n) + if len(ans) < len(n.word) or n.word < ans: + ans = n.word + return ans + + def longest2(self): + self.ans = '' + + def dfs(node): + for c, n in node.children.items(): + if n.end: + dfs(n) + if len(self.ans) < len(n.word) or (len(self.ans) == len(n.word) and self.ans > n.word): + self.ans = n.word + + dfs(self.root) + return self.ans + + +# print(Solution().longestWord( + # ["a", "banana", "app", "appl", "ap", "apply", "apple"])) +# print(Solution().longestWord(["w", "wo", "wor", "worl", "world"])) +# print(Solution().longestWord(["m", "mo", "moc", "moch", "mocha", + # "l", "la", "lat", "latt", "latte", "c", "ca", "cat"])) +# print(Solution().longestWord(["rac", "rs", "ra", "on", "r", +# "otif", "o", "onpdu", "rsf", "rs", "ot", "oti", "racy", "onpd"])) +# print(Solution().longestWord(["yo", "ew", "fc", "zrc", "yodn", +# "fcm", "qm", "qmo", "fcmz", "z", "ewq", "yod", "ewqz", "y"])) +# print(Solution().longestWord(["m", "mo", "moc", "moch", "mocha", +# "l", "la", "lat", "latt", "latte", "c", "ca", "cat"])) + + +# queue = collections.deque() +# for i in [1, 2, 3, 4, 5, 6, 7, 8]: +# queue.append(i) +# while queue: +# print(queue.pop()) diff --git a/Week_04/id_26/LeetCode_77_26.py b/Week_04/id_26/LeetCode_77_26.py new file mode 100644 index 00000000..a9f6c0f8 --- /dev/null +++ b/Week_04/id_26/LeetCode_77_26.py @@ -0,0 +1,53 @@ +# +# @lc app=leetcode.cn id=77 lang=python +# +# [77] 组合 +# +# https://leetcode-cn.com/problems/combinations/description/ +# +# algorithms +# Medium (68.18%) +# Likes: 125 +# Dislikes: 0 +# Total Accepted: 12.9K +# Total Submissions: 18.8K +# Testcase Example: '4\n2' +# +# 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 +# +# 示例: +# +# 输入: n = 4, k = 2 +# 输出: +# [ +# ⁠ [2,4], +# ⁠ [3,4], +# ⁠ [2,3], +# ⁠ [1,2], +# ⁠ [1,3], +# ⁠ [1,4], +# ] +# +# + + +class Solution(object): + def combine(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[List[int]] + """ + ans = [] + + def helper(path=[]): + if len(path) == k: + return ans.append(path) + for i in range(path[-1] + 1 if path else 1, n+1): + helper(path+[i]) + helper() + return ans + + +# print(Solution().combine(4, 2)) +# print(Solution().combine(0, 0)) diff --git a/Week_04/id_26/LeetCode_784_26.py b/Week_04/id_26/LeetCode_784_26.py new file mode 100644 index 00000000..70a1a5d6 --- /dev/null +++ b/Week_04/id_26/LeetCode_784_26.py @@ -0,0 +1,62 @@ +# +# @lc app=leetcode.cn id=784 lang=python +# +# [784] 字母大小写全排列 +# +# https://leetcode-cn.com/problems/letter-case-permutation/description/ +# +# algorithms +# Easy (55.43%) +# Likes: 76 +# Dislikes: 0 +# Total Accepted: 5.3K +# Total Submissions: 9.5K +# Testcase Example: '"a1b2"' +# +# 给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。 +# +# +# 示例: +# 输入: S = "a1b2" +# 输出: ["a1b2", "a1B2", "A1b2", "A1B2"] +# +# 输入: S = "3z4" +# 输出: ["3z4", "3Z4"] +# +# 输入: S = "12345" +# 输出: ["12345"] +# +# +# 注意: +# +# +# S 的长度不超过12。 +# S 仅由数字和字母组成。 +# +# +# + + +class Solution(object): + def letterCasePermutation(self, S): + """ + :type S: str + :rtype: List[str] + """ + paths = [] + + def helper(i, path=''): + if i == len(S): + return paths.append(path) + if S[i].isdigit(): + return helper(i+1, path+S[i]) + helper(i+1, path + S[i].lower()) + helper(i+1, path + S[i].upper()) + helper(0) + return paths + + +# print(Solution().letterCasePermutation('3z4')) +# print(Solution().letterCasePermutation('12345')) +# print(Solution().letterCasePermutation('a1b2')) +# print(Solution().letterCasePermutation('')) diff --git a/Week_04/id_26/LeetCode_78_26.py b/Week_04/id_26/LeetCode_78_26.py new file mode 100644 index 00000000..6953c202 --- /dev/null +++ b/Week_04/id_26/LeetCode_78_26.py @@ -0,0 +1,57 @@ +# +# @lc app=leetcode.cn id=78 lang=python +# +# [78] 子集 +# +# https://leetcode-cn.com/problems/subsets/description/ +# +# algorithms +# Medium (73.61%) +# Likes: 264 +# Dislikes: 0 +# Total Accepted: 22.9K +# Total Submissions: 31K +# Testcase Example: '[1,2,3]' +# +# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 +# +# 说明:解集不能包含重复的子集。 +# +# 示例: +# +# 输入: nums = [1,2,3] +# 输出: +# [ +# ⁠ [3], +# [1], +# [2], +# [1,2,3], +# [1,3], +# [2,3], +# [1,2], +# [] +# ] +# +# + + +class Solution(object): + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + paths = set() + + def helper(i, path=()): + paths.add(path) + if i == len(nums): + return + helper(i+1, path + (nums[i],)) + helper(i+1, path) + + helper(0) + return [list(i) for i in paths] + + +# print(Solution().subsets([1, 2, 3]))