题解
【入门】全部排列问题
2 条题解
-
0
#include <bits/stdc++.h> using namespace std; int a[10], n; //把当前排列出来的数进行输出 void print() { for (int i = 1; i <= n; i++) { cout << a[i]; } cout << endl; } void fun(int x) {//调用一次就是拼凑一位 //下标为x的位置又是n种可能(1~n) for (int i = 1; i <= n; i++) { a[x] = i; if (x == n) {//如果已经填到最后一个位置 print(); } else { fun(x + 1);//递归填写下一个位置 } } } int main() { cin >> n; fun(1); return 0; } -
0
#include <iostream> using namespace std; int a[100],n; void print(){ for(int i = 1;i <= n;i++){ cout<<a[i]; } cout<<endl; } //为下标为x的位置赋值 void fun(int x){ //下标为x的位置有n种赋值的可能 for(int i = 1;i <= n;i++){ a[x] = i;//每个位置都赋值i if(x == n){ //输出排列 print(); }else{ fun(x+1); } } } int main(){ cin>>n; fun(1);//从下标为1开始填起 }
- 1