当前位置:网站首页>LeetCode_46_全排列
LeetCode_46_全排列
2022-07-23 07:02:00 【Fitz1318】
题目链接
题目描述
给定一个不含重复数字的数组 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]]
提示:
1 <= nums.length <= 6-10 <= nums[i] <= 10nums中的所有整数 互不相同
解题思路
回溯法
这里需要注意的是要记录一个数字是否已经使用过了,因为题目中说了nums里面的数字互不相同,所以可以用path.contains(nums[i])来判断是否使用过了这个数字
回溯三部曲
- 递归函数参数
nums:给定的集合path:记录符合条件的结果ans:记录结果的集合
- 终止条件
- 找到叶子,即
path,size() == nums.length
- 找到叶子,即
- 单层逻辑
- 每次从投搜索,然后对已经使用过的数字进行跳过
AC代码
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<Integer> path = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
backTracing(nums, path, ans);
return ans;
}
private static void backTracing(int[] nums, List<Integer> path, List<List<Integer>> ans) {
if (path.size() == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (path.contains(nums[i])) {
continue;
}
path.add(nums[i]);
backTracing(nums, path, ans);
path.remove(path.size() - 1);
}
}
}
边栏推荐
- Knowledge map: basic concepts
- Chapter II relational database after class exercises
- Interface test - simple interface automation test demo
- [Muduo] epollplayer event distributor
- Point target simulation of SAR imaging (I) -- mathematical model
- Kept dual machine hot standby
- ROS中引用和输出消息类型
- 了解canvas
- Method of entering mathematical formula into mark down document
- 高性能JVM的参数
猜你喜欢
随机推荐
GLIB-CRITICAL g_file_test:assertion ‘filename != null‘ failed
docker mysql
Running matlab program on GPU
Reference and output message types in ROS
同花顺开户风险性大吗,安全吗?
[Muduo] poller abstract class
数据库-视图详探
About this pointer
数据库系统原理与应用教程(046)—— MySQL 查询(八):分组查询(GROUP BY)
Problem solving: script file 'scripts\pip script py‘ is not present.
专题讲座5 组合数学 学习心得(长期更新)
[play with FPGA in simple terms to learn 10 ----- simple testbench design]
Wu Enda machine learning series p31~p42
Talking about the CPU type of anroid device and the placement directory of so files
数据库系统原理与应用教程(040)—— MySQL 查询(二):设置要查询的列名或表达式
QNX修改系统时间
Special lecture 5 combinatorial mathematics learning experience (long-term update)
Special topic of MIMO Radar (0) - General Chapter
反常积分的审敛
MySQL index transaction & JDBC programming









