牛客题霸--字符串的排列

字符串的排列

https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=117&&tqId=35262&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

字符串的排列

题目链接

Solution

计算一个字符串的所有排列。
c++ stL库中有一个函数是可以按字典序大小计算出当前排列的下一个排列的,同样可以计算出上一个排列。
所以我们可以将字符串排序,然后依次计算下一个排列即可。

Code

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> ans;
        if (str.empty()) return ans;
        sort(str.begin(), str.end());
        do {
            ans.push_back(str);
        } while (next_permutation(str.begin(), str.end()));
        return ans;
    }    
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
6
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务