解题思路: 本题是一个典型的回溯问题, 回溯体遍历的时候每次只要交换当前索引和第i个索引就可以
class Solution {
List<List<Integer>> totlelist = new ArrayList<> ();
public List<List<Integer>> permute(int[] nums) {
solve(nums,0,new ArrayList<Integer>());
return totlelist;
}
private void solve(int[] nums,int start,List<Integer> list){
if(start == nums.length){
totlelist.add(new ArrayList<Integer>(list)); //要创建新的list
return;
}
for(int i=start;i<nums.length;i++){
swap(nums,start,i);
list.add(nums[start]);
solve(nums,start+1,list);
list.remove(list.size()-1); // list回溯过后要去掉
swap(nums,start,i); //要交换回来
}
}
private void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}