声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
Given a collection of distinct integers, return all possible permutations.
Brief
全排列问题。
Input
[1,2,3]
Output
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Ideas
主要的方法perm(int[] A,int p,int q)表示,将数组A中,p到q的所有数字的全排列加入到list中去。
在perm方法中,首先将每个数字都与开头数字p改变位置,然后求剩下p+1到q的全排列,最后将每个数字再与开头数字p改变位置。
Code
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0){
return res;
}
perm(nums,0,nums.length - 1);
return res;
}
public void swap(int[] A,int i,int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
public void perm(int[] A,int p,int q){
List<Integer> list = new ArrayList<>();
if(p == q){
for(int i = 0;i < A.length;i ++){
list.add(A[i]);
}
res.add(list);
}
for(int i = p;i <= q;i ++){
swap(A,p,i);
perm(A,p + 1,q);
swap(A,p,i);
}
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com