当前位置:网站首页>【回溯】全排列 leetcode46
【回溯】全排列 leetcode46
2022-06-30 21:30:00 【小风_】
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:输入:nums = [0,1] 输出:[[0,1],[1,0]]
示例 3:输入:nums = [1] 输出:[[1]]
链接:https://leetcode.cn/problems/permutations
很经典的回溯算法题基础,需要考虑递归树的状态、变量和返回是什么,在此题中,递归树的变量是每一次递归时的nums,根节点是本身,每一次递归会减少一个数,叶子节点就是nums为空的时候,进行返回。
class Solution:
def permute(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)):
helper(nums[:idx]+nums[idx+1:],his+[nums[idx]])
helper(nums,[])
return self.ret
边栏推荐
- 12345
- 興奮神經遞質——穀氨酸與大腦健康
- 1-15 nodemon
- 激发新动能 多地发力数字经济
- 1-21 jsonp interface
- Open source internship experience sharing: openeuler software package reinforcement test
- qsort函数和模拟实现qsort函数
- How to run jenkins build, in multiple servers with ssh-key
- Three techniques for reducing debugging time of embedded software
- USBCAN分析仪的配套CAN和CANFD综合测试软件LKMaster软件解决工程师CAN总线测试难题
猜你喜欢

Prediction and regression of stacking integrated model

Multi table operation - foreign key constraint

MySQL高级篇3

How to move forward when facing confusion in scientific research? How to give full play to women's advantages in scientific research?

Nacos部署及使用

qsort函数和模拟实现qsort函数

Reading notes of Clickhouse principle analysis and Application Practice (2)

Oracle 数据库表结构 Excel 导出

科研中遇到迷茫困惑如何向前一步?如何在科研中发挥女性优势?

Clickhouse native monitoring item, system table description
随机推荐
1-13 express监听GET和POST请求&处理请求
Clickhouse native monitoring item, system table description
Four Misunderstandings of Internet Marketing
Sqlserver gets the data of numbers, Chinese and characters in the string
文本生成模型退化怎麼辦?SimCTG 告訴你答案
12345
ca i啊几次哦啊句iu家哦
The 16th Heilongjiang Provincial Collegiate Programming Contest
Dm8: generate DM AWR Report
Adobe Photoshop (PS) - script development - remove file bloated script
A small step in code change and a big leap in thinking
jupyterbook 清空控制台输出
根据肠道微生物组重新思考健康饮食
Five years after graduation, I wondered if I would still be so anxious if I hadn't taken the test
It is urgent for enterprises to protect API security
ICLR'22 Spotlight | 怎样度量神经网络权重中的信息量?
Internet of things botnet gafgyt family and backdoor vulnerability exploitation of Internet of things devices
asp.net core JWT传递
1-15 nodemon
Iclr'22 spotlight | how to measure the amount of information in neural network weights?