DevYoon

[๋ฐฑ์ค€] 7490. 0 ๋งŒ๋“ค๊ธฐ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 7490. 0 ๋งŒ๋“ค๊ธฐ (Python)

gimewn 2022. 9. 4. 01:16

link ๐Ÿ”— https://www.acmicpc.net/problem/7490

 

7490๋ฒˆ: 0 ๋งŒ๋“ค๊ธฐ

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์— ๋Œ€ํ•ด ASCII ์ˆœ์„œ์— ๋”ฐ๋ผ ๊ฒฐ๊ณผ๊ฐ€ 0์ด ๋˜๋Š” ๋ชจ๋“  ์ˆ˜์‹์„ ์ถœ๋ ฅํ•œ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฒฐ๊ณผ๋Š” ํ•œ ์ค„์„ ๋„์›Œ ๊ตฌ๋ถ„ํ•œ๋‹ค.

www.acmicpc.net

 

๐Ÿ“Œ DFS๋กœ +, -, ๊ณต๋ฐฑ์˜ ๊ฒฝ์šฐ๋ฅผ ํƒ€๊ณ  ๋“ค์–ด๊ฐ€์ฃผ์—ˆ๋‹ค.

๐Ÿ“Œ DFS ๋‚ด๋ถ€์—์„œ ๊ณ„์‚ฐ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€์ง€๊ณ  ๋‹ค๋…€๋ณด์•˜๋Š”๋ฐ, ์ƒ๊ฐ์ฒ˜๋Ÿผ ๊ณ„์‚ฐ ๊ฒฐ๊ณผ๊ฐ€ ์ž˜ ๋‚˜์˜ค์ง€ ์•Š์•˜๋‹ค.

๐Ÿ“Œ ๋”ฐ๋ผ์„œ ๋งˆ์ง€๋ง‰ ์ˆซ์ž๋ฅผ ๋ชจ๋‘ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ, ๋งŒ๋“ค์–ด์ง„ ๋ฌธ์ž์—ด์„ eval ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด ๊ณ„์‚ฐํ•˜๊ณ , ๊ฐ’์ด 0์ด๋ฉด res ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ์‹์œผ๋กœ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

๐Ÿ“Œ ๋ฌธ์ž์—ด ๋‚ด๋ถ€์—์„œ ๊ณต๋ฐฑ์„ ์‚ฌ์šฉํ•œ ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•ด replace ๋ฉ”์†Œ๋“œ๋กœ ๊ณต๋ฐฑ์„ ์—†์• ์ค€ ํ›„ eval ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

 

def DFS(nowNum, sentence):
    if nowNum == N+1:
        test = eval(sentence.replace(" ", ""))
        if test == 0:
            res.append(sentence)
    else:
        DFS(nowNum+1, sentence+'+'+str(nowNum))
        DFS(nowNum + 1, sentence + '-'+str(nowNum))
        DFS(nowNum + 1, sentence + ' '+str(nowNum))

T = int(input())

for _ in range(T):

    N = int(input())
    res = []
    DFS(2, "1")

    res.sort()

    for s in res:
        print(str(s))

    print()