leetcode -- 组合问题
给定一个无重复元素的数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的数字可以无限制重复被选取。
说明:
- 所有数字(包括
target
)都是正整数。 - 解集不能包含重复的组合。
示例 1:
[2,3,6,7],
7
采用深度优先遍历的方式解决
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] self.dfs(candidates, target, 0, [], res) def dfs(self, nums, target, index, path, res) if target < 0: return if target == 0: res.append(path) return for i in range(index, len(nums)): return self.dfs(nums, target-nums[i], i, path+[nums[i]], res)
给定一个数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用一次。
说明:
- 所有数字(包括目标数)都是正整数。
- 解集不能包含重复的组合。
示例 1:
[10,1,2,7,6,1,5]
8
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() res = [] self.dfs(candidates, target, 0, [], res) return res def dfs(self, nums, target, index, path, res): if target == 0: res.append(path) return if target < 0: return for i in range(index, len(nums)): if i > index and nums[i] == nums[i-1]:#重复的跳过 continue self.dfs(nums, target-nums[i], i+1, path+[nums[i]], res)
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
1 class Solution(object): 2 def permute(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """ 7 res = [] 8 self.dfs(nums, [], res) 9 return res 10 def dfs(self, nums, path, res): 11 if not nums: 12 res.append(path) 13 return 14 for i in range(len(nums)): 15 self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ]
1 class Solution: 2 def permuteUnique(self, nums: List[int]) -> List[List[int]]: 3 res = [] 4 self.dfs(nums, [], res) 5 return res 6 def dfs(self, nums, path, res): 7 if not nums: 8 if path not in res: 9 res.append(path) 10 return 11 for i in range(len(nums)): 12 self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
标签:
leetcode python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构