题目
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int n = nums.length;
boolean[] used = new boolean[n];
LinkedList<Integer> path = new LinkedList<>();
dfs(nums, 0, used, path, result);
return result;
}
public void dfs(int[] nums, int index, boolean[] used, LinkedList<Integer> path, List<List<Integer>> res) {
if (index == nums.length) {
res.add(new LinkedList(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
path.add(nums[i]);
used[i] = true;
dfs(nums, index + 1, used, path, res);
used[i] = false;
path.removeLast();
}
}
}