Permutation II--LeetCode

痛定思痛。 2022-08-07 11:46 181阅读 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. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. /*
  5. 一个数组的排列
  6. */
  7. bool isValid(vector<int>& vec,int begin,int index)
  8. {
  9. int i;
  10. for(i = begin;i<index;i++)
  11. {
  12. if(vec[i] == vec[index])
  13. return false;
  14. }
  15. return true;
  16. }
  17. void Permutation(vector<int>& vec,int begin,int end)
  18. {
  19. int i=0;
  20. if(begin >= end)
  21. {
  22. for(i=0;i<vec.size();i++)
  23. cout<<vec[i]<<" ";
  24. cout<<endl;
  25. return ;
  26. }
  27. for(i=begin;i<=end;i++)
  28. {
  29. if(isValid(vec,begin,i))
  30. {
  31. swap(vec[begin],vec[i]);
  32. Permutation(vec,begin+1,end);
  33. swap(vec[begin],vec[i]);
  34. }
  35. }
  36. }
  37. int main()
  38. {
  39. vector<int> vec(3);
  40. int i;
  41. for(i=0;i<vec.size();i++)
  42. vec[i] = i+1;
  43. vec[1] =1;
  44. int pos =0;
  45. Permutation(vec,pos,2);
  46. return 0;
  47. }

发表评论

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

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

相关阅读