LeetCode46:
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

  1. class Solution {
  2. List<List<Integer>> list = new ArrayList<>();
  3. LinkedList<Integer> linkedList = new LinkedList<>();
  4. boolean[] used;
  5. public List<List<Integer>> permute(int[] nums) {
  6. int len = nums.length;
  7. if (len == 0) {
  8. return new ArrayList<>();
  9. }
  10. used = new boolean[len];
  11. permuteHelper(nums);
  12. return list;
  13. }
  14. private void permuteHelper(int[] nums) {
  15. if (linkedList.size() == nums.length) {
  16. list.add(new ArrayList<>(linkedList));
  17. return;
  18. }
  19. int len = nums.length;
  20. for (int i = 0; i < len; i++) {
  21. if (used[i]){
  22. continue;
  23. }
  24. used[i] = true;
  25. linkedList.addLast(nums[i]);
  26. permuteHelper(nums);
  27. linkedList.removeLast();
  28. used[i] = false;
  29. }
  30. }
  31. }

参考文献

  1. 46.全排列