面试题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;
}
posted @ 2020-08-18 17:10  程序员曾奈斯  阅读(149)  评论(0编辑  收藏  举报