๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Python] [Level1] ์‚ผ์ด์‚ฌ

Dbswnstjd 2023. 4. 10. 15:20

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/131705

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ - ์‚ผ์ด์‚ฌ
def solution(number):
    tot = 0
    def dfs(i, depth, sum_num):
        nonlocal tot

        if depth == 3 and sum_num == 0:
            tot += 1
            return

        if i == len(number):
            return

        if depth < 3:
            dfs(i+1, depth+1, sum_num + number[i])
            dfs(i+1, depth, sum_num)

    dfs(0,0,0)        

    answer = tot


    return answer

DFS๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€ ์ˆ˜ ์žˆ๋‹ค. 

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

def solution (number) :
    from itertools import combinations
    cnt = 0
    for i in combinations(number,3) :
        if sum(i) == 0 :
            cnt += 1
    return cnt
print(solution([-2, 3, 0, 2, -5]))

Combination ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•ด์„œ ๋ชจ๋“  ์กฐํ•ฉ์„ ๊ตฌํ•˜๊ณ  sum ์ด 0 ์ด๋ฉด cnt ๋ฅผ ์ฆ๊ฐ€ ์‹œ์ผœ์ฃผ๋Š” ํ’€์ด .