加载中...

DFS

DFS

DFS指数型枚举模板

image-20240412122753272

bbd1e15879cc804559cc6083bf2e141

#include<iostream>
using namespace std;

int arr[20];
int n;

void dfs(int x){
    if (x > n ){  // 出口 DFS位置大于选择的n
        
        for (int i = 1; i <=n ; ++i){
            if (arr[i] == 1){   // 如果标志为1 的 被选中的打印出
                cout << i << " ";
            }
    
        }
         cout << endl;
         return;
    }
    
    arr[x] = 1; // 选中
    dfs(x + 1); // DFS
    arr[x] = 0; // 回溯
    
    arr[x] = 2; // 不选中
    dfs(x + 1);  // DFS
    arr[x] = 0; // 回溯
}


int main(){
    cin >> n;
    dfs(1);
    
}

全排列

image-20240412124922322

微信图片_20240412131939

#include<bits/stdc++.h>
using namespace std;

int n;
bool st[20];
int arr[20];

void dfs(int x){
    // 出口条件
	if (x > n){
		for (int i = 1;i <= n ; ++i){
			cout <<"    "<< arr[i];
		}
		cout << endl;
		return;
	}
    
    // 三个分支
	for (int i = 1; i<= n; ++i){
        
		if (!st[i]){ // 如果这个数没被选中
			st[i] = true; // 上锁
			arr[x] = i; // 给予这个数
			dfs(x+1); // DFS
			st[i] = false; // 回溯
			arr[x] = 0;
		}
	}
}
int main(){
	cin >> n;
	dfs(1);
} 

DFS组合枚举

image-20240412132508989

#include<bits/stdc++.h>
using namespace std;
int n, r;
int arr[20];

void dfs(int x, int start){
	
	if (x > r){
		for ( int i = 1; i <= r ; ++i){
			cout << setw(3) << arr[i];
		}
		cout << endl;
		return;
	}
	
	for (int i = start ; i <= n ;++i ){
		arr[x] = i;
		dfs(x+1,i+1);
		arr[x] = 0;
	}
}

int main(){
	cin >> n >> r; 
	dfs(1,1);
	return 0;
} 
posted @ 2024-04-13 14:56  江寒雨  阅读(40)  评论(0)    收藏  举报