全排列

题目:

输入一个没有重复数字的序列,返回其所有可能的排列。

解答:

 1 public class Solution {
 2 
 3     public static List<List<Integer>> permute(int[] nums) {
 4         List<List<Integer>> result = new ArrayList<>();
 5 
 6         backtracking(result, nums, 0);
 7         return result;
 8 
 9     }
10 
11     private static void backtracking(List<List<Integer>> result, int[] nums, int j) {
12         if(j == nums.length) {
13             List<Integer> l = new ArrayList<>();
14             for(int num : nums) {
15                 l.add(num);
16             }
17 
18             result.add(l);
19         }
20 
21         for(int i = j; i < nums.length; i++) {
22             swap(nums, i, j);
23             backtracking(list, nums, j+1);
24 
25             // 回溯的意思就是要回去,递归函数自动保证了回去,但是我们设置的其他变量如果有必要的话也必须要回到原位
26             sawp(nums, i, j);
27         }
28     }
29 }
原文地址:https://www.cnblogs.com/wylwyl/p/10466401.html