[Algorithm] ๐Ÿšฉ์กฐํ•ฉ ๊ตฌํ•˜๊ธฐ (โญ์ค‘์š”!) (DFS)

myeonjiยท2022๋…„ 3์›” 3์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
60/89
post-custom-banner

โญ ์กฐํ•ฉ ๊ตฌํ•˜๊ธฐ์—์„œ ์‘์šฉ๋˜์–ด ๋ฌธ์ œ๊ฐ€ ๋งŽ์ด ์ถœ์ œ๋˜๋ฏ€๋กœ ์ค‘์š”ํ•œ ๋ถ€๋ถ„ !!

def DFS(L, s):
    global cnt
    if L == m:
        for x in result:
            print(x, end=' ')
        print()
        cnt += 1
        return
    else:
        for i in range(s, n+1):
            result[L] = i
            DFS(L+1, s+i)  # ์ด ๋ถ€๋ถ„ ํ‹€๋ฆผ!


n, m = map(int, input().split())
result = [0]*m
cnt = 0
DFS(0, 1)
print(cnt)

์ฒ˜์Œ์— ์œ„์ฒ˜๋Ÿผ ํ’€์—ˆ๋Š”๋ฐ ๋ช‡ ๊ตฐ๋ฐ์—์„œ wrong ์ด ๋–ด๋‹ค.

DFS(L+1, s+i)๊ฐ€ ์ž˜๋ชป๋˜์—ˆ๋Š”๋ฐ, ๊ฐ€์ง€์— +1์„ ํ•ด์•ผํ–ˆ๋‹ค.

def DFS(L, s):
    global cnt
    if L == m:
        for j in range(m):
            print(res[j], end=' ')
        cnt += 1
        print()
    else:
        for i in range(s, n+1):
            res[L] = i
            DFS(L+1, i+1)  # ๊ฐ€์ง€์— +1์„ ํ•ด์•ผํ•˜๋ฏ€๋กœ i+1


n, m = map(int, input().split())
res = [0]*(n+1)
cnt = 0
DFS(0, 1)
print(cnt)

์ด๋ ‡๊ฒŒ!!

๋งŒ์•ฝ s๊ฐ€ 2์ด๋ฉด ๊ฐ€์ง€๋Š” 2, 3, 4 ๋งŒ ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. 1์€ ์˜ค์ง€ ๋ชปํ•œ๋‹ค.
์กฐํ•ฉ ์ด๊ธฐ ๋•Œ๋ฌธ์— (1,3) ๊ณผ (3,1) ์ค‘์— ํ•˜๋‚˜๋งŒ ๊ฐ€๋Šฅํ•˜๋‹ค.

profile
DBA, ๊ฒฝ์ œ ๊ทธ๋ฆฌ๊ณ  ๊ณ ๋ƒฅ์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€