犯错,在backtracking和他的 的for循环里,我把下一次backtracking的函数里传入了现在的index+1,这样就造成的问题,是下一次加进list里,保证就是对应位置的数字,这样不能保证输出全排列,应该检查现在list里有没有这个数
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
对于Permutation的话,虽然有for循环,但不是每次都执行n次,所以时间复杂度应该是O(n!);而因为储存时有n!种排列,而每种排列记录的是n个数,所以空间复杂度应该是O(n*n!)
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0)
return res;
backtracking(res,nums, new ArrayList<>());
return res;
}
public void backtracking(List<List<Integer>> res, int[] nums, List<Integer> list){
if(list.size() == nums.length){
res.add(new ArrayList<>(list));
return;
}
else{
for(int i = 0; i< nums.length;i++){
if(list.contains(nums[i])) continue;
list.add(nums[i]);
backtracking(res,nums,list);
list.remove(list.size()-1);
}
}
}
}