字符串排序

题目

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

思路

递归思想,参考别人,感谢原作者。原文地址:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
固定第1位:让所有位依次作为第一位;
利用递归,其余位作为一个字符串继续排列,以此类推。
需要注意的是递归结束条件:排列开始位为字符串的最后一位则结束递归;

示例

输入:asdd
输出:
adds
adsd
asdd
dads
dasd
ddas
ddsa
dsad
dsda
sadd
sdad
sdda

代码

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using  namespace std;


class  Solution{
public:
    vector<string> Permutation(string str){
        vector<string> result;
        // 如果字符串为空返回空
        if (str.empty())
            return result;
        Permutation(str,result,0);
        // 排字典序
        sort(result.begin(),result.end());
        return result;

    }

private:
    void Permutation(string str, vector<string> &result, int begin) {
        // 结束递归条件
        if (begin == str.size() - 1) {
            // 判断字符串组,如果字符串已经存在就不在存储
            if (find(result.begin(), result.end(), str) == result.end())
                result.push_back(str);
        } else {
            for (int i = begin; i < str.size(); ++i) {
                swap(str[begin], str[i]);
                // 固定前面N为,对其余位进行排列
                Permutation(str, result, begin + 1);
                // 恢复原来位置,便于下一次排序
                swap(str[begin], str[i]);
            }
        }
    }
    void swap(char &a, char &b){
        char temp(a);
        a = b;
        b = temp;
    }
};
int main(){
    string input1("asdd");
    string input2("cbsd");
    Solution re;
    vector<string> result1(re.Permutation(input1));
    vector<string> result2(re.Permutation(input2));
    while (!result1.empty()){
        cout << result1.front() << endl;
        result1.erase(result1.begin());
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值