zoukankan      html  css  js  c++  java
  • STL next_permutation和prev_permutation函数

    利用next_permutation实现全排列升序输出,从尾到头找到第一个可以交换的位置,

    直接求到第一个不按升序排列的序列。

     1 #include <iostream>
     2 #include <algorithm>    /// next_permutation, sort
     3 #define MAX 100
     4 using namespace std;
     5 
     6 int main() {
     7     int myints[MAX],n;
     8     cin >> n;
     9     for (int i = 0; i < n; i++)
    10     {
    11         cin >> myints[i];
    12     }
    13     sort(myints, myints + n);
    14 
    15     do {
    16         for (int i = 0; i < n; i++)
    17         {
    18             cout << myints[i] <<" ";
    19         }
    20         cout << endl;
    21     } while (next_permutation(myints, myints + n));    ///获取下一个较大字典序排列
    22     
    23     system("pause");
    24     return 0;
    25 }

    同理,prev_permutation恰恰相反。

    附一个全排列字母输出的例子:

    题目描述

    输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。 
    输入描述:
    输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
     1 #include "iostream"
     2 #include "string"
     3 #include "vector"
     4 #include "algorithm"
     5 
     6 using namespace std;
     7 
     8 void Permutation(string str) {
     9     vector<char> sstr;
    10     for (int i = 0; i < str.length(); i++)
    11         sstr.push_back(str[i]);
    12 
    13 
    14      do {
    15          for (int i = 0; i < str.length(); i++)
    16          {
    17              cout << sstr[i] << " ";
    18          }
    19          cout << endl;
    20 
    21     } while (next_permutation(sstr.begin(), sstr.end()));
    22 
    23 }
    24 
    25 
    26 int main() {
    27     string str;
    28     while (cin >> str)
    29     {
    30         Permutation(str);
    31     }
    32     return 0;
    33 }
  • 相关阅读:
    MP3 PQF模块 matlab实现
    Warped Filter
    研究音频编解码要看什么书
    转:Firefox的未来版本可能备有内置视频聊天功能
    SILK,Speex,ISAC,AMRWB区别(1)
    SILK 的 Tilt的意思
    桓泽学音频编码
    整理下最近的学习思路(3月15日~4月9日)
    MPEG4 SSC备选标准SiCAS
    桓泽谈音乐(1)
  • 原文地址:https://www.cnblogs.com/SeekHit/p/5631121.html
Copyright © 2011-2022 走看看