首页 > 解决方案 > 产生给定长度的序列

问题描述

我正在寻找 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

我浏览了互联网,但只能得到给定输入长度的增加序列。我正在弄清楚如何产生这样的序列!

标签: algorithmdata-structures

解决方案


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

#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;
}

推荐阅读