This post is quite related with the previous question.
2023.03.21 - [Algorithm] - 백준 15649, 15650 python with Recurion and Backtracking
In 15649 show the result of Combination, this time we just want a Permutation
Problem #15650
https://www.acmicpc.net/problem/15651
15651번: N과 M (3)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
N, M = list(map(int, input().split()))
ans=[]
def dfs():
if(len(ans) == M):
print(*ans)
return
else:
for i in range (1, N+1):
ans.append(i)
dfs()
ans.pop()
dfs()
Simple note
Dude, we have actually used this algorithm before in problem #15649(almost same isn'it?).
For this particular problem, we don’t need to worry about having duplicates. So we just keep adding a value to our array from the beginning over and over again. That’s why I left the value of index i untouched.
Problem #15651
https://www.acmicpc.net/problem/15652
15652번: N과 M (4)
한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해
www.acmicpc.net
N, M = list(map(int, input().split()))
ans=[]
def dfs(a):
if len(ans)==M:
print(*ans)
return
else:
for i in range(a,N+1):
ans.append(i)
dfs(i)
ans.pop()
dfs(1)
By analyzing the desired output, It’s clear that each subsequent element is always greater than or equal to the previous one. Therefore, we modify the parameter of the recursive function to pass a larger value each time. It’s as simple as that.
'Algorithm' 카테고리의 다른 글
백준 15649, 15650 python with Recurion and Backtracking (0) | 2023.03.21 |
---|---|
Combination and Permutation with recursive algorithm (0) | 2023.01.25 |
Time Complexity: Big O notation (0) | 2023.01.22 |
다이나믹 프로그래밍 feat.백준 15990 python (0) | 2023.01.13 |