https://www.acmicpc.net/problem/15664
15664번: N과 M (10)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
[난이도] Silver2
[유형] 백트래킹
[풀이]
오름차순으로 출력해야 하기 때문에 정렬 후에 백트래킹을 해주면 됩니다.
중복 제거를 위해 set을 이용하였습니다.
#include <cstdio> #include <algorithm> #include <set> #include <vector> using namespace std; int N,M,a[8]; set<vector<int>> st; vector<int> ans; void sol(int n){ if(n==N){ if(ans.size()==M) { if(st.find(ans) == st.end()){ st.insert(ans); for(auto k : ans) printf("%d ",k); puts(""); } } return; } ans.push_back(a[n]); sol(n+1); ans.pop_back(); sol(n+1); } int main(){ scanf("%d%d",&N,&M); for(int i=0;i<N;i++) scanf("%d",&a[i]); sort(a,a+N); sol(0); }
https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Silver2/15664.cpp
'Problem-Solving > BOJ' 카테고리의 다른 글
[BOJ/백준][Silver3] 16967 : 배열 복원하기 (C++) (0) | 2022.11.06 |
---|---|
[BOJ/백준][Silver2] 2210 : 숫자판 점프 (C++) (0) | 2022.11.06 |
[BOJ/백준][Silver2] 1138 : 한 줄로 서기 (C++) (0) | 2022.11.06 |
[BOJ/백준][Silver2] 5397 : 키로거 (C++) (0) | 2022.11.06 |
[BOJ/백준][Silver1] 15903 : 카드 합체 놀이 (C++) (0) | 2022.11.06 |