排列生成算法

作者在 2010-12-24 15:26:13 发布以下内容
#include<iostream>
#include<sstream>
#include<algorithm>
using namespace std;
int main()
{
    int array[] = {0,1,2,3,4,5,6,7,8,9,10};
    int size = sizeof(array)/sizeof(int);
    int n;
    cin >> n;
    int* *index = new int*[size];
    for(int i = 0; i < size; ++i)
        index[i] = array+i;
    int j = n-2;
    n--;
    ostringstream s;
    int c = 0;
    while(1){
        for(int i = 0; i<n; ++i)
            s << *index[i] << ' ';
        while(i < size)
        {
            cout << s.str() << *index[i++] << endl;
            ++c;
        }
        s.seekp(0);
        while(index[j]>index[j+1] && index[j]>index[size-1])
            if(--j<0) goto done;
        sort(index+j+1,index+size);
        swap(*lower_bound(index+j+1,index+size,index[j]), index[j]);
        j = n-1;
    }
done:
    cout << endl << c << endl;
    return 0;
}
默认分类 | 阅读 1154 次
文章评论,共0条
游客请输入验证码
浏览30051次