46. 全排列

image.png
注意我们这次每次都重复去取元素,所以不需要starIndex,但是需要记录每个元素是否被用过,所以加入一个boolean[] used

  1. class Solution {
  2. List<List<Integer>> result = new ArrayList<>();
  3. List<Integer> path = new ArrayList<>();
  4. private void backTracking(int[] nums,boolean[] used){
  5. if (path.size() == nums.length){
  6. result.add(new ArrayList<>(path));
  7. return;
  8. }
  9. for (int i = 0; i < nums.length; i++) {
  10. if (used[i] == true){//true说明已经被用过,跳过
  11. continue;
  12. }
  13. used[i] = true;//因为用了,标志true
  14. path.add(nums[i]);
  15. backTracking(nums,used);
  16. used[i] = false;//回溯,重新标志false
  17. path.remove(path.size()-1);
  18. }
  19. }
  20. public List<List<Integer>> permute(int[] nums) {
  21. boolean[] used = new boolean[nums.length];
  22. backTracking(nums,used);
  23. return result;
  24. }
  25. }
  1. // 解法2:通过判断path中是否存在数字,排除已经选择的数字
  2. class Solution {
  3. List<List<Integer>> result = new ArrayList<>();
  4. LinkedList<Integer> path = new LinkedList<>();
  5. public List<List<Integer>> permute(int[] nums) {
  6. if (nums.length == 0) return result;
  7. backtrack(nums, path);
  8. return result;
  9. }
  10. public void backtrack(int[] nums, LinkedList<Integer> path) {
  11. if (path.size() == nums.length) {
  12. result.add(new ArrayList<>(path));
  13. }
  14. for (int i =0; i < nums.length; i++) {
  15. // 如果path中已有,则跳过
  16. if (path.contains(nums[i])) {
  17. continue;
  18. }
  19. path.add(nums[i]);
  20. backtrack(nums, path);
  21. path.removeLast();
  22. }
  23. }
  24. }

47. 全排列 II

image.png

  1. class Solution {
  2. List<List<Integer>> result = new ArrayList<>();
  3. List<Integer> path = new ArrayList<>();
  4. private void backTracking(int[] nums, boolean[] used) {
  5. if (nums.length == path.size()) {
  6. result.add(new ArrayList<>(path));
  7. return;
  8. }
  9. for (int i = 0; i < nums.length; i++) {
  10. if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue;
  11. if (used[i] == false) {
  12. used[i] = true;
  13. path.add(nums[i]);
  14. backTracking(nums, used);
  15. path.remove(path.size() - 1);
  16. used[i] = false;
  17. }
  18. }
  19. }
  20. public List<List<Integer>> permuteUnique(int[] nums) {
  21. Arrays.sort(nums);
  22. boolean[] used = new boolean[nums.length];
  23. backTracking(nums, used);
  24. return result;
  25. }
  26. }