分析递归的过程
#include<iostream>
using namespace std;int function(int n){if(n==1)return 1;if(n==2)return 2;return function(n-1)+function(n-2);
}
树的高度对应着DFS深度优先搜索,空间占用与树的高度
#include<iostream>
#include<algorithm>
#include<cstring>using namespace std;const int N=20;int n;
int st[N];//记录每个数的状态,0表示还没有考虑,1表示选,2表示不选void dfs(int x){//x表示当前枚举到了哪个位置if(x>n){for(int i=1;i<=n;i++){if(st[i]==1){printf("%d ",i);}}cout<<endl;return ;}//选st[x]=1;dfs(x+1);//深度搜索st[x]=0;//恢复现场//不选st[x]=2;dfs(x+1);st[x]=0;//恢复现场
}int main(){scanf("%d",&n);dfs(1);return 0;
}
全排列问题
1.依次枚举每个位置应该放哪个数
2.依次枚举每个数应该放哪个位置