1.题目描述
46. 全排列
给定一个 没有重复
数字的序列,返回其所有可能的全排列。
示例:
1 2 3 4 5 6 7 8 9 10
| 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
|
2.代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public List<List<Integer>> permute(int[] nums) { //创建一个集合用于返回 List<List<Integer>> perms = new ArrayList<>();
//调用函数得到想要的结果 permute_recursion(nums,0,perms);
return perms; }
private static void permute_recursion(int[] nums, int start_index, List<List<Integer>> perms) { int length = nums.length;
//当最后一位时,将得到的结果加入到返回的集合中 if (start_index == length-1){ List<Integer> list = new ArrayList<>();
for (int i = 0; i < length; i++) { list.add(nums[i]); }
perms.add(list); }else { for (int i = start_index; i <= length - 1; i++) { swap(nums,start_index,i); permute_recursion(nums,start_index+1,perms); swap(nums,start_index,i); } } }
/** * nums数组中交换索引为i和j两处的元素 * @param nums * @param i * @param j */ public static void swap(int[] nums, int i, int j){ int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; } }
|