产生给定长度的序列

时间:2018-06-08 10:37:59

标签: algorithm data-structures

我正在寻找C ++中的代码来产生这样的序列:
输入:
n = 4(序列中的最大元素),k = 3(序列长度)

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2 4
1 4 2
2 1 4
2 4 1
4 1 2
4 2 1

我通过互联网但只能获得increasing sequence of given input length。我正在弄清楚如何制作这样的序列!

1 个答案:

答案 0 :(得分:0)

我认为这就像你正在寻找的东西

#include <iostream>
#include <algorithm>
using namespace std;

int n, k;
int main(){
    cin>>n;
    cin>>k;
    int a[n];
    for(int i = 0; i < n; i++)
            a[i] = i + 1;
    do{
        for(int i = 0; i < k; i++)
                cout<<a[i]<<" ";
        cout<<endl;
    }while(next_permutation(a, a + n));
    return 0;
}