Leetcode: Permutations II

Bertha 。 2022-08-07 15:59 224阅读 0赞

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

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

这道题和前面Leetcode: Permutations类似,不过给定序列中有重复的序列。
采用Leetcode: Permutations思路二,不过我们在交换的过程中发现有相同元素出现的时候不进行交换就OK了。

C++参考代码:
(可以对比Leetcode: Permutations思路二的代码,其实两者改动的地方就是啊判断要不要交换)

  1. class Solution
  2. {
  3. private:
  4. vector<vector<int>> result;
  5. int size;
  6. //这个isSwap函数是比原来的Permutation I中新添加的函数
  7. //该函数用来判断current位置的元素要不要进行交换
  8. bool isSwap(vector<int> num, int begin, int current)
  9. {
  10. for (int i = begin; i < current; ++i)
  11. {
  12. if (num[i] == num[current]) return false;
  13. }
  14. return true;
  15. }
  16. void permuate(vector<int> &num, int index)
  17. {
  18. if (index == size)
  19. {
  20. result.push_back(num);
  21. return;
  22. }
  23. for (int i = index; i < size; ++i)
  24. {
  25. if (i != index && !isSwap(num, index, i)) continue;//这句是新添加的,用来判断如果给定的序列中有重复元素,则跳过重复元素
  26. swap(num[index], num[i]);//交换i和index元素
  27. permuate(num, index + 1);//计算除去index元素,后面元素的全排列
  28. swap(num[index], num[i]);//再换回来
  29. }
  30. }
  31. public:
  32. vector<vector<int> > permuteUnique(vector<int> &num)
  33. {
  34. size = int(num.size());
  35. permuate(num, 0);
  36. return result;
  37. }
  38. };

发表评论

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

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

相关阅读