题目: 全排列(Java)
内容
链接: 全排列
给定一个没有重复数字的序列,返回其所有可能的全排列。
用例
- 示例 1:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路
两种思路
1、回溯法。
AC代码
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length==0){
return res;
}
permuteCore(nums,0);
return res;
}
public void permuteCore(int[] nums, int lo) {
if (lo == nums.length -1) {
List<Integer> list = new ArrayList<>();
list=Arrays.stream(nums).boxed().collect(Collectors.toList());
if(!res.contains(list))
res.add(list);
return;
}
for(int i = lo; i< nums.length ;i++){
swap(nums, lo ,i);
permuteCore(nums,lo+1);
swap(nums, lo ,i);
}
}
public void swap(int[] nums ,int i, int j){
int temp = nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}