DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์†Œ์ˆ˜ ์ฐพ๊ธฐ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์†Œ์ˆ˜ ์ฐพ๊ธฐ (Python)

gimewn 2022. 4. 21. 00:00

link ๐Ÿ”— https://programmers.co.kr/learn/courses/30/lessons/42839

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์†Œ์ˆ˜ ์ฐพ๊ธฐ

ํ•œ์ž๋ฆฌ ์ˆซ์ž๊ฐ€ ์ ํžŒ ์ข…์ด ์กฐ๊ฐ์ด ํฉ์–ด์ ธ์žˆ์Šต๋‹ˆ๋‹ค. ํฉ์–ด์ง„ ์ข…์ด ์กฐ๊ฐ์„ ๋ถ™์—ฌ ์†Œ์ˆ˜๋ฅผ ๋ช‡ ๊ฐœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋‚ด๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ ์ข…์ด ์กฐ๊ฐ์— ์ ํžŒ ์ˆซ์ž๊ฐ€ ์ ํžŒ ๋ฌธ์ž์—ด numbers๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ข…์ด

programmers.co.kr

 

1๏ธโƒฃ DFS๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์ดํ–ˆ๋‹ค.

2๏ธโƒฃ ์ˆซ์ž์˜ ์ž๋ฆฟ์ˆ˜๊ฐ€ numbers์˜ ์ž๋ฆฟ์ˆ˜๋ณด๋‹ค ํฌ๋ฉด ์•ˆ ๋˜๋ฏ€๋กœ, ๋ ˆ๋ฒจ์ด numbers์˜ ์ž๋ฆฟ์ˆ˜๋ณด๋‹ค ๋” ์ปค์ง€๋ฉด ๋ฆฌํ„ดํ•ด์ฃผ์—ˆ๋‹ค.

3๏ธโƒฃ num์ด ์ตœ์ดˆ์˜ ์ƒํƒœ('')๊ฐ€ ์•„๋‹ˆ๊ณ , DFS์˜ ๋ณ€์ˆ˜๋กœ check ๋ฐฐ์—ด์„ ๋‘์–ด check ์•ˆ์— ์—†๋Š” ์ˆ˜๋งŒ ๊ฒ€์‚ฌํ•ด์ฃผ์—ˆ๋‹ค.

4๏ธโƒฃ ์‹œ๊ฐ„ ์ดˆ๊ณผ๋กœ ๋‹ต์ด ์•ˆ ๋‚˜์™€์„œ ์†Œ์ˆ˜ ๊ฒ€์‚ฌํ•˜๋Š” for๋ฌธ ์•ˆ์— break๋ฅผ ๋„ฃ์–ด์คฌ๋”๋‹ˆ ์ œ๋Œ€๋กœ ๋‹ต์ด ๋‚˜์™”๋‹ค.

 

def solution(numbers):
    answer = 0
    visit = [0]*len(numbers)
    def dfs(level, num, check):
        nonlocal answer
        if level == len(numbers)+1:
            return
        flag = 0
        if num != '' and int(num) > 1 and int(num) not in check:
            for i in range(2, int(num)):
                if int(num)%i == 0:
                    flag = 1
                    break
            if flag == 0:
                answer += 1
                check.append(int(num))
        for idx in range(len(numbers)):
            if visit[idx] == 1:continue
            new_num = num+numbers[idx]
            visit[idx] = 1
            dfs(level+1, new_num, check)
            visit[idx] = 0
    dfs(0, '', [])
    return answer