zoukankan      html  css  js  c++  java
  • 剑指offer38 字符串的排列

    思路:

    递归+回溯,关键是去重。

    实现1(在原字符串中通过交换的方式生成排列)

     1 class Solution
     2 {
     3 public:
     4     void dfs(string &s, int p, vector<string>& res)
     5     {
     6         int n = s.length();
     7         if (p == n - 1) { res.push_back(s); return; }
     8         vector<bool> vis(26, false);
     9         for (int i = p; i < n; i++)
    10         {
    11             int tmp = s[i] - 'a';
    12             if (vis[tmp]) continue;
    13             vis[tmp] = true;
    14             swap(s[p], s[i]);
    15             dfs(s, p + 1, res);
    16             swap(s[p], s[i]);
    17         }
    18     }
    19     vector<string> permutation(string s)
    20     {
    21         vector<string> res;
    22         dfs(s, 0, res);
    23         return res;
    24     }
    25 };

    实现2(开辟新的缓冲区,不断选取未使用过的字符追加到缓冲区末尾生成排列):

     1 class Solution
     2 {
     3 public:
     4     void dfs(string &s, string& t, vector<bool>& vis, vector<string>& res)
     5     {
     6         int n = s.length();
     7         if (t.length() == n) { res.push_back(t); return; }
     8         for (int i = 0; i < n; i++)
     9         {
    10             if (vis[i]) continue;
    11             if (i > 0 and s[i - 1] == s[i] and !vis[i - 1]) continue;
    12             vis[i] = true;
    13             t.push_back(s[i]);
    14             dfs(s, t, vis, res);
    15             t.pop_back();
    16             vis[i] = false;
    17         }
    18     }
    19     vector<string> permutation(string s)
    20     {
    21         sort(s.begin(), s.end());
    22         int n = s.length();
    23         vector<bool> vis(n, false);
    24         vector<string> res;
    25         string t = "";
    26         dfs(s, t, vis, res);
    27         return res;
    28     }
    29 };
  • 相关阅读:
    centos6.5升级gcc 4.4.7为最新版4.9.1
    vmware打开虚拟级断电情况下,无法找到虚拟机文件
    centos /usr/local 和/opt 安装软件你什么不同../configure --prefix=/usr...
    centos安装git
    P1207 双重回文数
    P1214 等差数列
    P1215 母亲的牛奶
    P1217 回文质数
    P3650 滑雪课程设计
    NOIP 2015[D2 T1] 跳石头
  • 原文地址:https://www.cnblogs.com/wangyiming/p/15141994.html
Copyright © 2011-2022 走看看