ํ’€์ด

์‹คํŒจํ–ˆ๋‹ค. ๋ญ”๊ฐ€ ๊ฐ์€ ์˜ค๋Š”๋ฐ ๊ธฐ์กด์˜ dp์ฒ˜๋Ÿผ ํ’€๋ ค๊ณ  ํ•˜๋‹ˆ ๋ฌธ์ œ๊ฐ€ ์•ˆ์žกํžˆ๋Š” ๊ธฐ๋ถ„. ์ผ๋‹จ ์ ‘๊ทผ ๋ฐฉ๋ฒ•์€ ๋งž์œผ๋‹ˆ, ์—‘์…€์ฒ˜๋Ÿผ ๋‚˜์—ดํ•˜๋ฉด์„œ ๊ทœ์น™์„ ์ฐพ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ๊ทธ๋ฆฌ๊ณ  dp์˜ ํ•ต์‹ฌ์€ ๊ธฐ์กด์˜ ์—ฐ์‚ฐ์ด ๋‚˜์ค‘์— ์—ฐ์‚ฐ์„ ํ•  ๋•Œ ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค๋Š” ๊ฒƒ์ธ๋ฐ, ์—ฌ๊ธฐ์„œ 1+1+1๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ 1+2์—์„œ ์ฒ˜๋ฆฌ๋œ๋‹ค๋Š” ๊ฒƒ์„ ๋ฐฐ์› ๋‹ค.

Code

def solution(N, number):
    # ์‚ฌ์šฉํ•œ N์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ˆ˜๋ฅผ ๋„ฃ์–ด๋‘ 
    # ์ผ๋‹จ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” N์˜ ๊ฐœ์ˆ˜๋Š” 8์ดํ•˜๊ธฐ ๋•Œ๋ฌธ์— 8๊ฐœ์˜ ๊ณต๊ฐ„์ด ์ƒ๊ธธ ์˜ˆ์ •
    
    # dp[i] = i๋ฒˆ N์„ ์‚ฌ์šฉํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ˆ˜
    
    dp = [ set([int(str(N)*x)]) if x != 0 else 0 for x in range(9)]
    
    for i in range(2, 9):
        for j in range(1, i): # j, i-j
            
            for a in dp[j]:
                for b in dp[i-j]:
                    dp[i].add(a+b)
                    if a-b >= 0:
                        dp[i].add(a-b)
                    else:
                        dp[i].add(b-a)
                    dp[i].add(a*b)
                    
                    if b != 0 and a%b == 0:
                        dp[i].add(int(a/b))
                    if a != 0 and b%a == 0:
                        dp[i].add(int(b/a))
    answer = -1
    for i in range(1, len(dp)):
        if number in dp[i]:
            answer = i
            break
    return answer

Reference