7번 문제

내가 풀이한 답

위의 그림과 같이 완전탐색으로 n 값에 대한 부분집합을 구할 수 있다. 해당 숫자를 포함하는 경우와 포함하지 않는 경우를 나누면 해결할 수 있다.
//#include <bits/stdc++.h> #include <iostream> using namespace std; int n, check[11]; void dfs(int level){ if(level==n+1){ for(int i=1; i<=n; i++){ if(check[i]==1) cout << i << " "; } cout << endl; } else { check[level] = 1; dfs(level+1); check[level] = 0; dfs(level+1); } } int main() { //freopen("input.txt", "rt", stdin); cin >> n; dfs(1); return 0; }
사이트의 답안
#include <stdio.h> #include <vector> #include <algorithm> using namespace std; int n, ch[100]; void DFS(int L){ int i; if(L==n+1){ for(i=1; i<=n; i++){ if(ch[i]==1) printf("%d ", i); } puts(""); } else{ ch[L]=1; DFS(L+1); ch[L]=0; DFS(L+1); } } int main(){ freopen("input.txt", "rt", stdin); scanf("%d", &n); DFS(1); return 0; }
'알고리즘 & 자료구조 > 그래프' 카테고리의 다른 글
9. 특정 수 만들기(DFS 완전탐색: MS 인터뷰) (0) | 2020.10.22 |
---|---|
8. 합이 같은 부분집합(DFS 완전탐색 : 아마존 인터뷰) (0) | 2020.10.22 |
6. 전위순회, 중위순회, 후위순회 (0) | 2020.10.21 |
5. 최소비용(DFS : 가중치 방향그래프 인접리스트) (0) | 2020.09.23 |
4. 최소비용(DFS : 인접행렬) (0) | 2020.09.23 |