• [LintCode] 带重复元素的排列


    递归实现:

     1 class Solution {
     2 public:
     3     /**
     4      * @param nums: A list of integers.
     5      * @return: A list of unique permutations.
     6      */
     7     vector<vector<int> > permuteUnique(vector<int> &nums) {
     8         // write your code here
     9         sort(nums.begin(), nums.end());
    10         vector<vector<int> > permutations;
    11         if (nums.empty()) return permutations;
    12         permutate(nums, 0, permutations);
    13         return permutations;
    14     }
    15 private:
    16     void permutate(vector<int> nums, int start, vector<vector<int> >& permutations) {
    17         if (start == nums.size()) {
    18             permutations.push_back(nums);
    19             return;
    20         }
    21         for (int i = start; i < (int)nums.size(); i++) {
    22             if (i == start || nums[i] != nums[start]) {
    23                 swap(nums[start], nums[i]);
    24                 permutate(nums, start + 1, permutations);
    25             }
    26         }
    27     }
    28 };

    非递归实现(基于nextPermutation):

     1 class Solution {
     2 public:
     3     /**
     4      * @param nums: A list of integers.
     5      * @return: A list of unique permutations.
     6      */
     7     vector<vector<int> > permuteUnique(vector<int> &nums) {
     8         // write your code here
     9         vector<vector<int> > permutations;
    10         if (nums.empty()) return permutations;
    11         vector<int> copy(nums.begin(), nums.end());
    12         nextPermutation(nums);
    13         permutations.push_back(nums);
    14         while (nums != copy) {
    15             nextPermutation(nums);
    16             permutations.push_back(nums);
    17         }
    18         return permutations;
    19     }
    20 private:
    21     void nextPermutation(vector<int>& nums) {
    22         int k = -1, n = nums.size();
    23         for (int i = n - 2; i >= 0; i--) {
    24             if (nums[i] < nums[i + 1]) {
    25                 k = i;
    26                 break;
    27             }
    28         }
    29         if (k == -1) {
    30             reverse(nums.begin(), nums.end());
    31             return;
    32         }
    33         int l;
    34         for (int i = n - 1; i > k; i--) {
    35             if (nums[i] > nums[k]) {
    36                 l = i;
    37                 break;
    38             }
    39         }
    40         swap(nums[l], nums[k]);
    41         reverse(nums.begin() + k + 1, nums.end());
    42     }
    43 };
  • 相关阅读:
    Visual Studio.Net 已检测到指定的Web服务器运行的不是ASP.NET1.1版。您将无法运行ASP.NET Web应用程序或服务。
    ActiveX 部件不能创建对象
    XML Schema帮你建模
    XBRL CHINA - XBRL入门
    Xml文档验证—编程篇
    怎样用XML技术对数据库进行操作
    Vclskin 问答
    Altova XMLSpy Ent 2006 汉化特别版 破解版
    一个通过DataSet操作XML的类
    XML Schema教程
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4625832.html
Copyright © 2020-2023  润新知