问题原始链接 https://leetcode.com/problems/permutations
给定一个由不同数组成的集合,返回所有可能的排列。
例如,[1,2,3] 有以下排列。
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
public class Solution {
public static List<List<Integer>> permute(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
p(nums, 0, result);
return result;
}
private static void p(int[] a, int i, List<List<Integer>> result) {
if (i == a.length - 1) {
result.add(toList(a));
return;
}
p(a, i + 1, result);
for (int j = i + 1; j < a.length; j++) {
swap(a, i, j);
p(a, i + 1, result);
swap(a, i, j);
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static List<Integer> toList(int[] a) {
List<Integer> result = new ArrayList<Integer>(a.length);
for (Integer i : a) {
result.add(i);
}
return result;
}
}