题目链接
题目描述
给定一个不含重复数字的数组 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] <= 10
nums
中的所有整数 互不相同
解题思路
回溯法
这里需要注意的是要记录一个数字是否已经使用过了,因为题目中说了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);
}
}
}