作为一个编程小白,刚看这个题目的时候,就有了这样一个疑问:“咦?这玩意儿是怎么递归的?”
好吧,这真是个小白会问的问题 _(:зゝ∠)_。有这个问题的小伙伴应该是递归这一部分的知识没有把握好,可以先去看看有关递归的知识(就像我一样 (┬_┬) )
话说这代码真的挺有趣,直接上代码吧。
#include<iostream>
using namespace std;
void print_permutation(int n, int*A, int cur)//permutation:排列、序列(其实俺也不知道,刚刚才百度过的)
{
if (cur == n)
{
for (int i = 0; i < n; i++)
cout << A[i]<<' ';
cout << endl;
}
else for (int i = 1; i <= n; i++)
{
int ok = 1;
for (int j = 0; j < cur; j++)
if (A[j] == i) ok = 0;
if (ok)
{
A[cur] = i;
print_permutation(n, A, cur + 1);
}
}
}
int main()
{
int A[100];
int n;
cin >> n;
print_permutation(n, A, 0);
}
***************************************************************************************************************************
接下来我(弱弱地)说一下 这个函数是怎么递归的,我相信肯定会有和我一样的小白的(偷笑.....)
(如上图)递归的重点就是在这里
再次上图(嘻嘻..这次是手写的,字丑.....)
另外,接下来这张图应该也能帮助大家理解这道题........~( ̄▽ ̄~)(~ ̄▽ ̄)~
——————————————————————————————分割线————————————————————————————————————
原来在STL里面还有个库函数哇,(┬_┬),那我就补充一下这个代码吧,好简单....
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n, p[10];
cin >> n;
for (int i = 0; i < n; i++) cin >> p[i];
sort(p, p + n);
do
{
for (int i = 0; i < n; i++)
cout << p[i];
cout << endl;
}
while (next_permutation(p, p + n));
return 0;
}
(如果有错误请大家指出来,我会万分感谢的,避免因为我的才疏学短误导了大家)