当前位置:网站首页>【回溯】全排列 II leetcode47
【回溯】全排列 II leetcode47
2022-06-30 21:30:00 【小风_】
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。 示例 1: 输入:nums = [1,1,2] 输出:
[[1,1,2], [1,2,1], [2,1,1]] 示例 2: 输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
链接:https://leetcode.cn/problems/permutations-ii
思路:和lc46不一样的地方在于,含有重复数字,此时,借鉴数组总和II的思路,首先讲序列进行排序,然后每次遍历的时候for循环判断下一个数字是否和上一个相同,相同的自动忽略(剪枝)掉,以此达到去重的目的
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
self.ret = []
'''NOTE 1.思考递归树(根节点和中间节点是什么) 2.思考递归树的每一个状态(for循环条件) 3.思考递归树的变量有哪些(回溯函数的形参) 4.思考递归树的叶子节点是什么(到哪结束return并保存什么) '''
def helper(nums:list,his:list):
if len(nums)==0:
self.ret.append(his)
return
for idx in range(len(nums)):
if idx!=0 and nums[idx]==nums[idx-1]: # 去重小技巧
continue
helper(nums[:idx]+nums[idx+1:],his+[nums[idx]])
nums.sort()
helper(nums,[])
return self.ret
边栏推荐
- 激发新动能 多地发力数字经济
- Adobe-Photoshop(PS)-脚本开发-去除文件臃肿脚本
- Apply for vector bus protocol color picture wallpaper hanging picture, very good!
- asp. Net core JWT delivery
- Clickhouse distributed table engine
- . NETCORE redis geo type
- Go build server Foundation
- A group of K inverted linked lists
- Sqlserver string type converted to decimal or integer type
- 升级kube出现unknown flag: --network-plugin
猜你喜欢
随机推荐
1-15 nodemon
攻防演练中的防泄露全家福
NCAT detailed introduction (Reprint)
Arcmap|assign values to different categories of IDS with the field calculator
Introduction of 3D Max fine model obj model into ArcGIS pro (II) key points supplement
Encryption and decryption and the application of OpenSSL
Side sleep ha ha ha
针对美国国家安全局“酸狐狸”漏洞攻击武器平台的分析与应对方案建议
What about degradation of text generation model? Simctg tells you the answer
漫谈Clickhouse Join
The 16th Heilongjiang Provincial Collegiate Programming Contest
1-12 初步认识Express
布隆过滤器
利用日志服务器输出各种apache的日志的TOPN
Adobe-Photoshop(PS)-脚本开发-去除文件臃肿脚本
What happens when word encounters an error while trying to open a file?
Random talk about Clickhouse join
[grade evaluator] how to register a grade evaluator? How many passes?
两个skyline
clickhouse原生監控項,系統錶描述







