public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
// Arrays.sort(nums); // not necessary
boolean[] visited = new boolean[nums.length];
backtrack(list, visited, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, boolean[] visited, List<Integer> tempList, int [] nums){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
return;
}
for(int i = 0; i < nums.length; i++){
// List.contains() 复杂度O(n)
// if (tempList.contains(nums[i])) continue;
if (visited[i]) continue; // element already exists, skip
visited[i] = true;
tempList.add(nums[i]);
backtrack(list, visited, tempList, nums);
// 回溯
tempList.remove(tempList.size() - 1);
visited[i] = false;
}
}
46. Permutations (无重复的全排列)
最新推荐文章于 2023-11-02 00:04:09 发布