46.Permutations (Medium)](https://leetcode.com/problems/permutations/description/)
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
题目描述:
给定一个数组,返回数组中元素所能组成的所有序列。
思路分析:
排列问题,可以用回溯的思路进行解决
代码:
public List<List<Integer>>permute(int []nums){
List<List<Integer>>res=new ArrayList<>();
if(nums==null||nums.length=0)
return res;
List<Integer>list=new ArrayList<>();
boolean []visited=new boolean[nums.length];
backtracking(nums,visited,res,list);
return res;
}
public void backtracking(int[]nums,boolean []visited,List<List<Integer>>res,List<Integer>list){
if(list.size()==nums.length){
res.add(new ArrayList<>(list));//重新构造一个List
return;
}
for(int i=0;i<nums.length;i++){
if(visited[i]==true)
continue;
visited[i]=true;
list.add(nums[i]);
backtracking(nums,visited,res,list);
list.remove(list.size()-1);
visited[i]=false;
}
}