zoukankan      html  css  js  c++  java
  • 关于全排列 next_permutation() 函数的用法

    这是一个c++函数,包含在头文件<algorithm>里面,下面是基本格式。

    1 int a[];
    2 do{
    3     
    4 }while(next_permutation(a,a+n));

    下面的代码可产生1~n的全排列。

    #include <stdio.h>
    #include <algorithm>
    using namespace std;
    int main(){
        int n;
        while(scanf("%d",&n)&&n){
            int a[1000];
            for(int i=0;i<n;i++){
                scanf("%d",&a[i]);
            }
            sort(a,a+n);//可以自行测试一下删除后的结果
            do{
                for(int i=0;i<n;i++)
                    printf("%d ",a[i]);
                printf("
    ");
            }while(next_permutation(a,a+n));
        }
        return 0;
    }

    例如输入

    3

    1 0 2

    如果有sort()

    输出为

    0 1 2
    0 2 1
    1 0 2
    1 2 0
    2 0 1
    2 1 0

    若无

    则输出为

    1 0 2
    1 2 0
    2 0 1
    2 1 0

    可以发现少了许多种组合方法。

    不过,仔细比较各种组合方法和有无sort()的输出,可以发现函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。

  • 相关阅读:
    17. Letter Combinations of a Phone Number
    16. 3Sum Closest
    15. 3Sum
    14. Longest Common Prefix
    13. Roman to Integer
    12. Integer to Roman
    11. Container With Most Water
    10. Regular Expression Matching
    9. Palindrome Number
    8. String to Integer (atoi)
  • 原文地址:https://www.cnblogs.com/My-Sunshine/p/4985366.html
Copyright © 2011-2022 走看看