给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [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 boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
List<List<Integer>> result = new ArrayList<List<Integer>>();//结果
List<Integer> path = new ArrayList<>();//一组解集
dfs(result,path,nums);
return result;
}
public void dfs (List<List<Integer>> result,List<Integer> path,int[] nums){
if(path.size() == nums.length){
result.add(new ArrayList<>(path));//已经找到一组解,加入到数组
}
for(int i = 0;i < nums.length;i++){//遍历条件数组
if(!path.contains(nums[i])){
path.add(nums[i]);//加入到路径
dfs(result,path,nums);//开始dfs
path.remove(path.size()-1);//撤销选择
}
}
}
}