ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - N์œผ๋กœ ํ‘œํ˜„

 

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ํŠน์ •ํ•œ ์ˆซ์ž `N`์œผ๋กœ ์‚ฌ์น™์—ฐ์‚ฐ์„ ์‚ฌ์šฉํ•˜์—ฌ `number`๋ฅผ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋•Œ `N`์„ ์‚ฌ์šฉํ•œ ํšŸ์ˆ˜๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๊ฒฝ์šฐ๋ฅผ ์ฐพ์•„์•ผ ํ•œ๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” `DP`๋ฅผ ํ†ตํ•ด์„œ๋„ ํ’€ ์ˆ˜ ์žˆ์ง€๋งŒ, `DFS`๋ฅผ ํ†ตํ•ด ํ’€๋”๋ผ๋„ ๊ฐ„์‹ ํžˆ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 `DFS`๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉํ•œ `N`์˜ ์ˆ˜๋ฅผ ์นด์šดํŠธํ•˜๊ณ , ์นด์šดํŠธ๋œ ์ˆ˜๊ฐ€ 8๋ณด๋‹ค ํฌ๋‹ค๋ฉด ๋” ์ด์ƒ ๊ฐ€์ง€๋ฅผ ๋ป—์„ ํ•„์š” ์—†์ด ์ข…๋ฃŒํ•˜๋ฉด ๋œ๋‹ค. ๋˜ํ•œ ๋งŒ์กฑํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ์€ ๊ฒฝ์šฐ, ํ˜„์žฌ ์ฐพ์€ ์นด์šดํŠธ๋ณด๋‹ค `N`์„ ๋” ๋งŽ์ด ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ๊ฐ€์ง€๋ฅผ ๋ป—์ง€ ์•Š์œผ๋ฉด ๋ณด๋‹ค ์‹œ๊ฐ„์„ ๋‹จ์ถ•์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from math import inf


answer = inf


def dfs(n, cnt, num, number):
    global answer

    if answer < inf and cnt > answer:
        return
        
    if cnt > 8:
        return

    if num == number:
        answer = min(answer, cnt)
        return

    next_num = 0
    for i in range(8):
        next_num = next_num * 10 + n
        dfs(n, cnt + 1 + i, num + next_num, number)
        dfs(n, cnt + 1 + i, num - next_num, number)
        dfs(n, cnt + 1 + i, num * next_num, number)
        dfs(n, cnt + 1 + i, num / next_num, number)


def solution(N, number):
    dfs(N, 0, 0, number)
    return -1 if answer == inf else answer

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€