![[백준 / BOJ] 15651번 N과 M (3) (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FOy7cb%2FbtrJqK7d67p%2FHLLTffbRmKrG4gbwbDhie1%2Fimg.png)
[백준 / BOJ] 15651번 N과 M (3) (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 7. 27. 22:31
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/15651
15651번: N과 M (3)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
문제

문제 풀이
앞선 문제들(N과 M (1), N과 M (2))와 같은 맥락을 공유하는 문제다.
이번 문제는 같은 수를 여러 번 골라도 된다는 조건이 붙어있다. 그래서 굳이 visited를 사용할 필요 없이, 그냥 dfs를 통해서만 해결하면 된다. (자세한 풀이는 N과 M (1) 문제를 참고해주세요.)
for (int i = 1; i <= N; i++) {
v[val] = i;
dfs(v, N, M, val + 1);
}
C++ 코드다. 해당 for문에서, 중복이 허용되므로 vector에 i를 저장한 후 dfs를 호출할 시 val 값을 한번 더 증가시켜준 값으로 넣어준다면 자연스레 v[val] = i에 순서대로 값이 넣어진다.
for i in range(1, N + 1):
res.append(i)
dfs(res, N, M, val + 1)
res.pop()
파이썬 코드다. 마찬가지로 val 인자만 +1 해주므로 중복을 허용하면서 뽑게 된다.
C++ 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
void dfs(std::vector<int> &v, int N, int M, int val) { | |
if (val == M + 1) { | |
for (int i = 1; i <= M; ++i) | |
std::cout << v[i] << " "; | |
std::cout << "\n"; | |
return; | |
} | |
for (int i = 1; i <= N; i++) { | |
v[val] = i; | |
dfs(v, N, M, val + 1); | |
} | |
} | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int N, M; | |
std::cin >> N >> M; | |
std::vector<int> v(M + 1); | |
dfs(v, N, M, 1); | |
return 0; | |
} |
Python 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
input = sys.stdin.readline | |
def dfs(res, N, M, val): | |
if M + 1 == val: | |
print(' '.join(map(str, res))) | |
return | |
for i in range(1, N + 1): | |
res.append(i) | |
dfs(res, N, M, val + 1) | |
res.pop() | |
N, M = map(int, input().split()) | |
res = [] | |
dfs(res, N, M, 1) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 9663번 N-Queen (C++, Python) (0) | 2022.08.05 |
---|---|
[백준 / BOJ] 15652번 N과 M (4) (C++, Python) (0) | 2022.07.31 |
[백준 / BOJ] 15650번 N과 M (2) (C++, Python) (0) | 2022.07.09 |
[백준 / BOJ] 15649번 N과 M (1) (C++, Python) (0) | 2022.07.07 |
[백준 / BOJ] 2004번 조합 0의 개수 (C++, Python) (0) | 2022.06.20 |
@Reo :: 코드 아카이브
자기계발 블로그