力扣 46. 全排列

题目说明

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

  • 提示:
    • 1 <= nums.length <= 6
    • -10 <= nums[i] <= 10
    • nums 中的所有整数 互不相同

示例

示例 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]]

示例 2:

1
2
输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

1
2
输入:nums = [1]
输出:[[1]]

笔者理解

此题是一道数组算法问题,在力扣题库中被定义为中等题。

解法

当笔者阅读完此题后,采用了回溯的办法,本题是经典的回溯问题,试探并回退就是精髓,让我们来看看具体如何实现的吧。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int [] tick = new int[nums.length];
List<Integer> temp = new ArrayList<>();
recall(result, tick, temp, nums);

return result;
}

/**
* result 结果集
* tick 标记当前元素是否被使用过
* temp 暂存元素组合序列
* nums 元素数组
*/
public void recall(List<List<Integer>> result, int[] tick, List<Integer> temp, int[] nums) {
if (temp.size() == nums.length) {
result.add(new ArrayList<>(temp));
return ;
}

for (int i = 0; i < nums.length; i++) {
if (tick[i] == 1) {
continue;
}
tick[i] = 1;
temp.add(nums[i]);
recall(result, tick, temp, nums);
tick[i] = 0;
temp.remove(temp.size() - 1);
}
}
}

时间和空间效率还行,可见此解法还比较适合此题。

image-20210909145957519

总结

本题是今天的一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。