[leetcode]46. Permutations全排列

Given a collection of distinct integers, return all possible permutations.

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

题意:

打印全排列

思路:

非常经典需要掌握的backtracking题 

形式化的表示递归过程:permutations(nums[0...n-1]) = {取出一个数字} + permutations(nums[0...n-1] - 该数字)

代码:

 1 class Solution {
 2     public List<List<Integer>> permute(int[] nums) {
 3         List<List<Integer>> result = new ArrayList<>();
 4         if(nums == null || nums.length == 0) return result;
 5         helper (nums, 0, result);
 6         return result;   
 7     }
 8     
 9     public static void helper(int[]nums, int index, List<List<Integer>> result){
10         if(index== nums.length){
11             List<Integer> path = new ArrayList<>();
12             for(int n: nums){
13                 path.add(n);
14             }
15             result.add(new ArrayList<>(path));
16             return;
17         }
18         
19         for(int i = index; i < nums.length; i++){
20             swap(nums, index, i);
21             helper(nums,index + 1, result);
22             swap(nums, index, i);
23         }
24     }
25     
26     public static void swap(int[]nums, int l, int r){
27         int temp = nums[l];
28         nums[l] = nums[r];
29         nums[r] = temp;
30     }
31 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9201935.html