LeetCode 第46题 全排列

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

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路:
dfs

1) 将每个元素放到他可能存在的位置,效率较低,每次需花O(n) 时间检查该元素是否被选取过
比如: [1 ,2 ,3]

   root
   / | \
   / | \
下标0: 1 2 3
/ \ / \ / \
下标1: 2 3 1 3 1 2
/ \ / \ / \
下标2: 3 2 3 1 2 1


2) 通过元素之间的互相交换,效率较高,不需要检查是否被选取过


 1 class Solution46 {
 2 
 3   List<List<Integer>> res = new ArrayList<>();
 4   List<Integer> list = new ArrayList<>();
 5 
 6   public List<List<Integer>> permute(int[] nums) {
 7     search(0, nums);
 8     return res;
 9   }
10 
11   void search(int level, int[] nums) {
12     if (level == nums.length) {
13       res.add(new ArrayList<>(list));
14     }
15     for (int num : nums) {
16       if (!list.contains(num)) {
17         list.add(num);
18         search(level + 1, nums);
19         list.remove((Integer) num);
20       }
21     }
22   }
23 }
24 
25 
26 ======================================
27 
28 
29 
30 class Solution46_2 {
31 
32   List<List<Integer>> res = new ArrayList<>();
33 
34 
35   public List<List<Integer>> permute(int[] nums) {
36     if (nums == null || nums.length == 0) {
37       return res;
38     }
39     search(0, nums);
40     return res;
41   }
42 
43   private void swap(int[] nums, int pos1, int pos2) {
44     int temp = nums[pos1];
45     nums[pos1] = nums[pos2];
46     nums[pos2] = temp;
47   }
48 
49   private void search(int index, int[] nums) {
50     if (index == nums.length) {
51       List<Integer> list = new ArrayList<>();
52       for (int num : nums) {
53         list.add(num);
54       }
55       res.add(list);
56     } else {
57       for (int i = index; i < nums.length; i++) {
58         swap(nums, index, i);
59         search(index + 1, nums);
60         swap(nums, index, i);
61       }
62     }
63   }
64 }


猜你喜欢

转载自www.cnblogs.com/rainbow-/p/10508908.html
今日推荐