全排序

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

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
 1 public void backtrack(int n,
 2                         ArrayList<Integer> output,
 3                         List<List<Integer>> res,
 4                         int first) {
 5     // 所有数都填完了
 6     if (first == n)
 7       //这里不能使用res.add(output)
 8       res.add(new ArrayList<Integer>(output));
 9     for (int i = first; i < n; i++) {
10       // 动态维护数组
11       Collections.swap(output, first, i);
12       // 继续递归填下一个数
13       backtrack(n, output, res, first + 1);
14       // 撤销操作
15       Collections.swap(output, first, i);
16     }
17   }
18 
19   public List<List<Integer>> permute(int[] nums) {
20     List<List<Integer>> res = new LinkedList();
21 
22     ArrayList<Integer> output = new ArrayList<Integer>();
23     for (int num : nums)
24       output.add(num);
25 
26     int n = nums.length;
27     backtrack(n, output, res, 0);
28     return res;
29   }

思路:https://leetcode-cn.com/problems/permutations/

posted @ 2020-08-26 10:35  王余阳  阅读(208)  评论(0)    收藏  举报