面试题38:字符串的排列

一、题目

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

二、解法

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> res;
        if(str!="" && str.size()>0)
            PermutationHelper(str, 0, res);
        sort(res.begin(), res.end());
        return res;
    }
    
    void PermutationHelper(string str, int begin, vector<string> &res)
    {
        if(begin == str.size()-1)
            res.push_back(str);
        for(int i=begin; i<=str.size()-1; ++i)
        {
            if(i!=begin&&str[i]==str[begin])
                continue;
            swap(str[i], str[begin]);
            PermutationHelper(str, begin+1, res);
            swap(str[i], str[begin]);
        }
    }
};

python版本

def Permutation(string):
    length = len(string)
    string = list(string)
    return PermutationCore(string, 0)

def PermutationCore(string, begin):
    if(begin==len(string)-1):
        print(string)
    else:
        for i in range(begin, len(string)):
            string[begin], string[i] = string[i], string[begin]
            PermutationCore(string, begin+1)
            string[i], string[begin] = string[begin], string[i]

猜你喜欢

转载自blog.csdn.net/sinat_36161667/article/details/80862055