题目
给定一个不含重复数字的数组 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中的所有整数 互不相同
题解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used = new boolean[nums.length];
backtrack(nums, used, path, res);
return res;
}
// 回溯函数
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
// 终止条件:path长度等于数组长度,找到一组排列
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue; // 当前数字已经选过,跳过
}
// 做选择
used[i] = true;
path.add(nums[i]);
// 递归
backtrack(nums, used, path, res);
// 撤销选择(回溯)
path.remove(path.size() - 1);
used[i] = false;
}
}
}