LC 46 Permutations(M)
解题思路 采用Recursive
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
} else{
//依次把值放入 tempList,如果已经有,就跳过
for(int i = 0; i < nums.length; i++){
if(tempList.contains(nums[i])) continue; // element already exists, skip
//一旦有新值放入,递归循环到下一个长度
tempList.add(nums[i]);
backtrack(list, tempList, nums);
//删除最后的值,看能不继续加新的值
tempList.remove(tempList.size() - 1);
}
}
}
Code flow
1 -> 1,2 -> 1,2,3
1,3 -> 1,3,2
2 -> 2,1 -> 2,1,3
2,3 -> 2,3,1
3 -> 3,1 -> 3,1,2
3,2 -> 3,2,1Last updated