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

    题目描述

    输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

    输入描述:

    输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

    分析:回溯法。

     1 class Solution {
     2 private:
     3     void dfs(vector<string> &res, string &s, vector<bool> &visited, const string str, int depth, int len) {
     4         if (depth == len - 1) {
     5             if (find(res.begin(), res.end(), s) == res.end()) { //find函数在头文件algorithm中
     6                 res.push_back(s);
     7             }
     8             return ;
     9         }
    10         for (int i = 0; i < len; i++) {
    11             if ( !visited[i]) {
    12                 visited[i] = true;
    13                 s += str[i];
    14                 dfs(res, s, visited, str, depth + 1, len);
    15                 s.pop_back();
    16                 visited[i] = false;
    17             }
    18         }
    19     }
    20 public:
    21     vector<string> Permutation(string str) {
    22         sort(str.begin(), str.end());
    23         vector<string> res;
    24         string s;
    25         int len = str.length();
    26         vector<bool> visited(len, false);
    27         for (int i = 0; i < len; i++) {
    28             visited[i] = true;
    29             s += str[i];
    30             dfs(res, s, visited, str, 0, len);
    31             s.pop_back();
    32             visited[i] = false;
    33         }
    34         return res;
    35     }
    36 };
  • 相关阅读:
    Java 分支结构
    Java 循环结构
    Java 运算符
    Java 修饰符
    Alpha冲刺——Day 6
    Alpha冲刺——Day 5
    Alpha冲刺——Day 4
    Alpha冲刺——Day 3
    Alpha冲刺——Day 2
    Alpha冲刺——Day 1
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11381534.html
Copyright © 2011-2022 走看看