Algorithm/BOJ
[백준/15650] N과 M (2) (with 파이썬)
Potato potage
2022. 12. 28. 23:09
반응형
✔ 문제
✔ 풀이
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
res = []
def dfs(x):
if len(res) == m:
print(' '.join(map(str, res)))
return
for i in range(x, n+1):
if i not in res:
res.append(i)
dfs(i + 1)
res.pop()
dfs(1)
✔ 설명
재귀함수를 이용해서 풀 수 있다.
for문에서 (시작, n+1)까지를 범위로 잡아 dfs를 돌면 된다.
ex) dfs(1) > res[1]
> dfs(2) > res[1, 2]
> dfs(3) > len(res) == 2 이므로 print, return
> pop() > res[1] > res[`, 3]
이런 흐름으로 진행된다.
✔ 후기
문제 보면서 dfs도 될 것 같다고는 느꼈지만 dfs로도 된다!
굳이 itertools 사용 없어도 dfs로 간단하게 풀 수 있었다.
참고:
https://jiwon-coding.tistory.com/22
[백준] 15650번 N과 M(2) / 파이썬(python)
# 문제 링크 www.acmicpc.net/problem/15650 15650번: N과 M (2) 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야
jiwon-coding.tistory.com
반응형