题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
boolean[] visited = new boolean[nums.length];
dfs(nums,new ArrayList<Integer>(),res,0,visited);
return res;
}
//dfs void 参数
void dfs(int[] nums,List<Integer> path,List<List<Integer>> res,int index,boolean[] visited){
//截止条件
if(index==nums.length){
res.add(new ArrayList<Integer>(path));
return;
}
//候选结点 ---没有重复 需要用visited保证 每一轮的结果没有重复值
for(int i=0;i<nums.length;i++){
if(visited[i]){
continue;
}
visited[i]=true;
path.add(nums[i]);
dfs(nums,path,res,index+1,visited);
path.remove(path.size()-1);
visited[i]=false;
}
}
}