LeetCode 47. Permutations II (Java版; Meidum)

曾经终败给现在 2023-07-21 11:27 108阅读 0赞

welcome to my blog

LeetCode 47. Permutations II (Java版; Meidum)

题目描述

  1. Given a collection of numbers that might contain duplicates, return all possible unique permutations.
  2. Example:
  3. Input: [1,1,2]
  4. Output:
  5. [
  6. [1,1,2],
  7. [1,2,1],
  8. [2,1,1]
  9. ]

第一次做; 核心: 1) 递归函数逻辑: 处理完[0,i], 当前处理索引i处的元素; [i,n-1]范围上的元素都没用过; HashSet去重, 防止索引i处使用重复的元素

  1. class Solution {
  2. public List<List<Integer>> permuteUnique(int[] nums) {
  3. List<List<Integer>> list = new ArrayList<>();
  4. List<Integer> al = new ArrayList<>();
  5. core(list, al, nums, 0);
  6. return list;
  7. }
  8. //递归函数逻辑: [0,i]上的结果
  9. private void core(List<List<Integer>> list, List<Integer> al, int[] nums, int i){
  10. //base case
  11. if(i==nums.length){
  12. list.add(new ArrayList<Integer>(al));
  13. return;
  14. }
  15. //
  16. int index=i;
  17. //记录当前位置出现过的数字
  18. HashSet<Integer> set = new HashSet<>();
  19. for(int k=i; k<nums.length; k++){
  20. int cur = nums[k];
  21. if(set.contains(cur)){
  22. continue;
  23. }
  24. swap(nums, index, k);
  25. al.add(cur);
  26. set.add(cur);
  27. core(list, al, nums, i+1);
  28. //
  29. al.remove(al.size()-1);
  30. swap(nums, index, k);
  31. }
  32. }
  33. private void swap(int[] arr, int i, int j){
  34. int tmp = arr[i];
  35. arr[i] = arr[j];
  36. arr[j] = tmp;
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,108人围观)

还没有评论,来说两句吧...

相关阅读