leetcode--Permutations II

Dear 丶 2021-10-25 12:38 374阅读 0赞

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].

  1. public class Solution {
  2. /**
  3. * To obtain a new permutation, given a permutation, we need to implement a series of swaps between
  4. * two indices. All swaps are represented by indices as the following form (i, j), where i <= j.<br>
  5. * So, in order to get all permutations, we only need to implements O(n^2) swaps.
  6. * @param num -int array
  7. * @return List<List<Integer> > -all permutations
  8. * @author Averill Zheng
  9. * @version 2014-06-24
  10. * @since JDK 1.7
  11. */
  12. public List<List<Integer>> permuteUnique(int[] num) {
  13. List<List<Integer> > result = new ArrayList<List<Integer> >();
  14. int length = num.length;
  15. if(length > 0){
  16. List<Integer> startPermutation = new ArrayList<Integer>();
  17. for(int s : num)
  18. startPermutation.add(s);
  19. result.add(startPermutation);
  20. //classify all swaps into groups(1, j), (2, j), ...(length - 2, j)
  21. for(int i = 0; i < length - 1; ++i){
  22. List<List<Integer> > tempResult = new ArrayList<List<Integer> >();
  23. while(!result.isEmpty()){
  24. List<Integer> oldPermutation = result.remove(0);
  25. //use a HashSet to record the duplications.
  26. Set<Integer> alreadySwapped = new HashSet<Integer>();
  27. //j starts from i, NOT i + 1, because we need to save original permutation back to tempResult
  28. for(int j = i; j < length; ++j) {
  29. if(!alreadySwapped.contains(oldPermutation.get(j))) {
  30. List<Integer> newListBySwapping = new ArrayList<Integer>();
  31. newListBySwapping.addAll(oldPermutation);
  32. //swap oldPermutation.get(i) and oldPermutation.get(j)
  33. int valueAtJ = oldPermutation.get(j);
  34. newListBySwapping.set(j, oldPermutation.get(i));
  35. newListBySwapping.set(i, valueAtJ);
  36. alreadySwapped.add(valueAtJ);
  37. tempResult.add(newListBySwapping);
  38. }
  39. }
  40. }
  41. result = tempResult;
  42. }
  43. }
  44. return result;
  45. }
  46. }

  

  

转载于:https://www.cnblogs.com/averillzheng/p/3542227.html

发表评论

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

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

相关阅读

    相关 安装IIS

    Windows Server版的操作系统装好后会默认装上IIS。但我们个人用的操作系统比如Window 10没有默认安装IIS,需要手动安装。 1.打开控制面板,点击程序

    相关 IIS5 IIS6 IIS7区别

    ASP.NET是一个非常强大的构建Web应用的平台,它提供了极大的灵活性和能力以致于可以用它来构建所有类型的Web应用。  绝大多数的人只熟悉高层的框架如: WebForm