• 面试题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;
    }
    
  • 相关阅读:
    ps:图层知识
    ps:选区的存储及载入
    ps:消除锯齿和羽化
    ps:不规则选区
    ps:建立规则选区
    python如何查看内存占用空间
    python-生成器
    python3-列表生成式
    python:迭代
    Photoshop画笔工具的使用
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13524573.html
Copyright © 2020-2023  润新知