加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++ 全排列

发布时间:2020-12-16 10:49:23 所属栏目:百科 来源:网络整理
导读:? 按顺序输出n位数的全排列,n位数为1-n。如n=3,则输出123,132,213,231,312,321 #include bits/stdc++.h using namespace std; int main(){ int n; cin n; int num[ 10 ]; for ( int i = 1 ;i = n;++ i) num[i - 1 ] = i; do { for ( int j = 0 ;j n;j++ )

?

按顺序输出n位数的全排列,n位数为1-n。如n=3,则输出123,132,213,231,312,321

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int num[10];
    for(int i = 1;i <= n;++i)
        num[i-1] = i;
    do{
        for(int j = 0;j < n;j++)
            cout << num[j];
        cout << endl;
    }while(next_permutation(num,num+n));
}

参考文章:https://www.cnblogs.com/aiguona/p/7304945.html

1)next_permutation:求下一个排列组合 

a.函数模板:next_permutation(arr,arr+size);
b.参数说明:
  arr: 数组名
  size:数组元素个数
c.函数功能: 返回值为bool类型,当当前序列不存在下一个排列时,函数返回false,否则返回true,排列好的数在数组中存储

d.注意:在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。
    比如,如果数组num初始化为2,3,1,那么输出就变为了:{2 3 1} {3 1 2} {3 2 1}

2)prev_permutation:求上一个排列组合

a.函数模板:prev_permutation(arr,arr+size);
b.参数说明:
  arr: 数组名
  size:数组元素个数
c.函数功能: 返回值为bool类型,当当前序列不存在上一个排列时,函数返回false,否则返回true
d.注意:在使用前需要对欲排列数组按降序排序,否则只能找出该序列之后的全排列数。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读