题目

类型:回溯

难度:中等

全排列 - 图1

解题思路

全排列 - 图2

代码

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