[模板] - 全排列

全排列

STL全排列

bool next_permutation(iterator start, iterator end);
The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.

#include 
#include 
int main() {
    char s[]="abc";
    while(next_permutation(s,s+3)) puts(s);
}

output:
acb
bac
bca
cab
cba

DFS输出1~n全排列

//按字典序输出1~n的全排列
int a[1005];
void print(int n, int cur) {
    if(cur == n) {
        for(int i=0 ; i1 ; i++) printf("%d ",a[i]);
        printf("%d\n",a[n-1]);
    }
    else {
        for(int i=1 ; i<=n ; i++) {
            bool flag=true;
            for(int j=0 ; jif(i==a[j]) flag=false;
            }
            if(flag) { a[cur]=i;
                //cout << a[cur] << endl;
                print(n, cur+1);
            }
        }
    }
}
int main()
{
    int n;
    cin >> n;
    print(n, 0);
    return 0;
}

你可能感兴趣的:(模板,ACM)