文章标题

来源:互联网 发布:windows网络命令 编辑:程序博客网 时间:2024/06/05 06:36

全排序的实现
引用:http://blog.csdn.net/morewindows/article/details/7370155/
递归实现:

#include<iostream>#include<algorithm>#include<string>#include<string.h>#include<vector>#include<stack>#include<set>#include<stdio.h>using namespace std;int cnt = 0;void swap(char *c1, char *c2) {    char t = *c1;    *c1 = *c2;    *c2 = t;}void AllRange(char s[], int k, int n) {    if(k == n) {        printf("%d: %s\n", ++cnt, s);        return;    }    AllRange(s, k+1, n);    set<char> st;    st.insert(s[k]);    for(int i = k + 1; i <= n; i++) {        if(st.count(s[i])) continue;        st.insert(s[i]);        swap(s+k, s+i);        AllRange(s, k+1, n);        swap(s+k, s+i);    }}int main() {    char s[100];    while(~scanf("%s", s)) {        cnt = 0;        AllRange(s, 0, strlen(s)-1);    }}

2.非递归实现

#include<iostream>#include<algorithm>#include<string>#include<string.h>#include<vector>#include<stack>#include<set>#include<stdio.h>using namespace std;void swap(char *c1, char *c2) {    char t = *c1;    *c1 = *c2;    *c2 = t;}bool tnext_permutation(char c[]) {    int n = strlen(c);    if(n == 0) return false;    for(int i = n - 2; i >= 0; i--) {        if(c[i] < c[i+1]) {            int k = i + 1;            for(int j = i + 2; j < n; j++) {                if(c[j] < c[k] && c[j] > c[i]) {                    k = j;                }            }            swap(c+i, c+k);            sort(c+i+1, c+n);            return true;        }    }    sort(c, c+n);    return false;}int main() {    char s[100];    while(~scanf("%s", s)) {        int cnt = 0;        int n = strlen(s);        sort(s, s+n);        do{            cout<<++cnt<<": "<<s<<endl;        }while(tnext_permutation(s));    }}

c++头文件中包含了全排序函数
next_permutation(a,a+3)
与prev_permutation(a, a+3)

0 0
原创粉丝点击