樹形結構的3中搜索方式示例分享
/**
樹的3中常見搜索方式
1.二叉樹方式(每一層只有0和1)
2.滿m叉樹(每一層都有0 到m - 1)
3.子集樹,也稱為全排列樹
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 20;
int n, m;
int ans[M];
//二叉樹
void dfs_two(int cur){
if(cur == n){
for(int i = 0; i < n; i++){
cout << ans[i] << " ";
}
cout << endl;
return;
}
ans[cur] = 1;
dfs_two(cur + 1);
ans[cur] = 0;
dfs_two(cur + 1);
}
//m叉樹
void dfs_m(int cur){
if(cur == n){
for(int i = 0; i < n; i++){
cout << ans[i] << " ";
}
cout << endl;
return ;
}
for(int i =0; i < n; i++){
ans[cur] = i;
dfs_m(cur + 1);
}
}
bool vis[M];
//子集樹
void dfs_sub(int cur){
if(cur == n){
for(int i = 0; i < n; i++){
cout << ans[i] << " ";
}
cout << endl;
return;
}
for(int i = 0; i < n; i++){
if(false == vis[i]){
vis[i] = true;
ans[cur] = i;
dfs_sub(cur + 1);
vis[i] = false;
}
}
}
int main(){
n = 5;
memset(ans, -1, sizeof(ans));
memset(vis, false, sizeof(vis));
dfs_two(0);//二叉樹搜索
dfs_m(0);//滿m叉樹搜索
dfs_sub(0);//子集樹搜索
return 0;
}
相關文章
c/c++靜態(tài)庫之間相互調用的實戰(zhàn)案例
C++調用C的函數比較簡單,直接使用extern "C" {}告訴編譯器用C的規(guī)則去編譯C代碼就可以了,下面這篇文章主要給大家介紹了關于c/c++靜態(tài)庫之間相互調用的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08