原题链接
https://leetcode.com/problems/permutations/description/
题目描述
Given a collection of distinct integers, return all possible permutations.
Example
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
两种典型的代码:
代码一:采用swap方法
该方法的思想相当于,每次将Index与之后的数字进行交换,相当于依次将每个数变成第一个数,之后再递归计算index+1之后的全排列
class Solution {
public List<List<Integer>> permute(int[] nums) {
if(nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
permute(ans, list, 0, nums);
return ans;
}
private void permute(List<List<Integer>> ans, List<Integer> list, int index, int[] nums) {
if(list.size() == nums.length) {
ans.add(new ArrayList<Integer>(list));
return;
}
for(int i = index; i < nums.length; i++) {
swap(i, index, nums);
list.add(nums[index]);
permute(ans,list, index+1, nums);
swap(i, index, nums);
list.remove(list.size() - 1);
}
}
private void swap(int i, int j, int[] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
代码二:使用used数组
每次遍历的时候查找还没使用的数字加入列表中
class Solution {
public List<List<Integer>> permute(int[] nums) {
if(nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
boolean[] flag = new boolean[nums.length];
permute(ans, list, flag, nums);
return ans;
}
private void permute(List<List<Integer>> ans, List<Integer> list, boolean[] flag, int[] nums) {
if(list.size() == nums.length) {
ans.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if(!flag[i]) {
list.add(nums[i]);
flag[i] = true;
permute(ans, list, flag, nums);
list.remove(list.size() - 1);
flag[i] = false;
}
}
}
}