zoukankan      html  css  js  c++  java
  • 面试题38:字符串的排列

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

    解题思路

    • 回溯法,easy
    • 只不过要注意判断字符可能出现连续的重复,则需要判断

    上代码(C++香)

    #include <iostream>
    #include <algorithm>
    #include <math.h>
    #include <cstring>
    #include "ListNode.h"
    #include "TreeNode.h"
    #include "Graph.h"
    using namespace std;
    
    #define MAXNUM 100010
    #define DRIFT 1001
    
    
    bool isSwap(char arr[], int len, int index){
        for(int i = index + 1; i < len; i++){
            if(arr[i] == arr[index])
                return false;
        }
        return true;
    }
    
    void mySwap(char str[], int i, int j){
        char temp = str[j];
        str[j] = str[i];
        str[i] = temp;
    }
    
    void dfs(char str[], int n, int index, vector<string> &vec){
        // 如果走到最后一步了
        if(index == n){
            vec.push_back(str);
            return ;
        }
    
        // 回溯法开始,每一步一个脚印
        for(int i = index; i < n; i++){
            if(isSwap(str, n, i)){
                //任取一个元素放在index位置
                mySwap(str, index, i);
                dfs(str, n, index + 1, vec);
                // 换回来
                mySwap(str, index, i);
            }
        }
        // 执行完就回溯
    }
    
    vector<string> Permutation(string str) {
        vector<string> vec;
        if(str.length() == 0)
            return vec;
        char myStr[str.length() + 1];
        for(int i = 0; i < str.length(); i++)
            myStr[i] = str[i];
        dfs(myStr, str.length(), 0, vec);
        return vec;
    }
    
    int main()
    {
        vector<string> vec = Permutation("abbcc");
        for(int i = 0; i < vec.size(); i++)
            cout<<vec[i]<<endl;
        return 0;
    }
    
  • 相关阅读:
    EF Core 打印日志
    生成各种开源挂件的网址
    .NET Core 原生 Aop,不依赖任何第三方
    .NET Core + Castle.DynamicProxy 拦截
    EF Core 审计日志
    Gitee 接口大全
    VS 批量新增文件头
    Linq 完全指南
    swagger转word
    大型网站架构
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13524573.html
Copyright © 2011-2022 走看看