不会递归真的很懵逼~~~
描述:给定一个数n,0<n<10,求出由数字1~n的构成的所以字典序
例如:n==3
1
2
3
1 2
1 3
2 3
1 2 3
#include<stdio.h>
#include<string.h>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const ll maxn=20;
//ll dp[10][10],a[10][10];
int p,a[maxn];
void print()
{
for(int i=1;i<=p;i++)
{
if(a[i])
cout<<a[i]<<" ";
}
cout<<endl;
}
int check()
{
int ans=0;
for(int i=1;i<=p;i++)
{
if(a[i])
ans++;
}
return ans;
}
void solve(int x,int y) //x:值,y:个数
{
if(x>p||check()>=y)
return ;
a[x]=x;
if(check()==y)
print();
else
solve(x+1,y);
a[x]=0;
solve(x+1,y);
}
int main()
{
cin>>p;
int t=1;
while(t<=p)
{
solve(1,t);
t++;
}
return 0;
}

本文介绍了一种使用递归方法解决给定数字范围内所有可能序列的字典序排列问题,通过实现一系列函数,从数字1到n构建了所有可能的组合,并以清晰的代码示例进行了展示。
504

被折叠的 条评论
为什么被折叠?



