Algorithm/etc

순열 구하기 - DFS

DingCoDing 2022. 1. 20. 18:46
반응형
#include <bits/stdc++.h>
using namespace std;

int n,r,ch[20],path[20],cnt;
vector<int> v;

//----


void DFS(int L){
	if(L==r){
		for(int i=0; i<L;i++){
			printf("%d ",path[i]);
		
		}
		cnt++;
		printf("\n");
	
	}
	else{
		
		
		for(int i=0; i<v.size(); i++){
			if(ch[v[i]]==0){
				path[L]= v[i];	
				ch[v[i]] = 1;
				DFS(L+1);
				
				ch[v[i]] = 0;
			}
		}
		
		
	}
	
	
}

int main(){
	//freopen("input.txt.txt","rt",stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);
	int tmp;
	
	scanf("%d %d",&n,&r);
	for(int i=0; i<n; i++){
		scanf("%d", &tmp);
		v.push_back(tmp);
	}
	DFS(0);
	printf("%d",cnt);
}

DFS를 활용해 순열을 구할 수 있다.

반응형