力扣链接:. - 力扣(LeetCode)
回溯,需要使用used数组表示该数有没有被使用过
class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> temp = new ArrayList<>();int[] nums, used;public List<List<Integer>> permute(int[] nums) {this.nums = nums;used = new int[nums.length];dfs();return ans;}void dfs() {if (temp.size() == nums.length) {ans.add(new ArrayList(temp));return;}for (int i = 0; i < nums.length; i++) {if (used[i] == 0) {used[i] = 1;temp.add(nums[i]);dfs();temp.remove(temp.size() - 1);used[i] = 0;}}}
}