美文网首页C++
使用C++ STL的next/prev_permutation函

使用C++ STL的next/prev_permutation函

作者: codinRay | 来源:发表于2017-04-07 20:54 被阅读0次

    使用C++ STL的next_permutation函数可以简单的枚举出一个升序排列的字符串的全排列,它包含在头文件<algorithm>里。

    用C类型字符串举一个例子:

    int main() {
        char str[] = "321";
        int len = strlen(str);
        sort(str, str + len);
        puts(str);
        while(next_permutation(str, str + len)) {
            puts(str);
        }
        return 0;
    }
    

    另外,prev_permutation函数可以枚举出一个降序排列的字符串的全排列。

    为了使字符串更方便的被降序排列,我们引入:

    sort(arr, arr + size, greater<int>());
    

    用以上的方式可以将int类型数组arr降序排列,同理可以使用在字符串上。

    所以:

    int main() {
        char str[] = "132";
        sort(str, str + strlen(str), greater<int>());
        while(prev_permutation(str, str + strlen(str)))
            puts(str);
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:使用C++ STL的next/prev_permutation函

        本文链接:https://www.haomeiwen.com/subject/euckattx.html