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;
    }
    
  • 相关阅读:
    java中动态给sql追加?号
    在java中构建json对象,返回给前端页面
    java中的文件下载
    Session和Cookie
    处理全站请求编码,无论是GET还是POST,默认是UTF-8
    配置Spring的用于初始化容器对象的监听器
    在web.xml中配置struts2拦截器
    java生成一次性验证码
    tab------左右布局
    java使用Base64编码
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13524573.html
Copyright © 2011-2022 走看看