提交时间:2026-01-17 20:35:51
运行 ID: 202414
#include <iostream> #include <algorithm> // 这个头文件是为了用 next_permutation 工具函数,固定加就行 using namespace std; int main() { // 1. 定义变量,输入要排列的数字n int n; cout << "请输入数字n:"; cin >> n; // 2. 定义【普通数组】存 1,2,3,...,n (你百分百学过的普通数组) // 数组开大小10足够用了,因为n一般输入1~9,不会太大 int arr[10]; for(int i = 0; i < n; i++) { arr[i] = i + 1; // 给数组赋值:下标0存1,下标1存2... } // 定义变量,统计总共有多少种排列 int total = 0; // 3. 核心:固定写法,生成并输出所有排列 // do-while循环:先执行内容,再判断条件,刚好输出第一个排列 do { // 输出当前这一组排列(一行输出一个排列) for(int i = 0; i < n; i++) { cout << arr[i]; } cout << endl; // 输出完一个排列后换行 total++; // 每输出一种,计数+1 } while( next_permutation(arr, arr + n) ); // 自动生成下一个排列 // 4. 最后输出总排列数 cout << "总排列数:" << total << endl; return 0; }