๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/131705
ํ์ด
# ํ๋ก๊ทธ๋๋จธ์ค 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 ๋ฅผ ์ฆ๊ฐ ์์ผ์ฃผ๋ ํ์ด .
'๐๏ธ Algorithm > โฌ ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
โฌ [Programmers] [Python] [Level1] ๊ฐ์ฅ ๊ฐ๊น์ด ๊ฐ์ ๊ธ์ (0) | 2023.04.10 |
---|---|
โฌ [Programmers] [Python] [Level1] ํธ๋ ํ์ดํธ ๋ํ (0) | 2023.04.10 |
โฌ [Programmers] [Python] [Level1] ์ด์ํ ๋ฌธ์ ๋ง๋ค๊ธฐ (0) | 2023.04.10 |
โฌ [Programmers] [Python] [Level1] ๋ฌธ์์ด ๋ด ๋ง์๋๋ก ์ ๋ ฌํ๊ธฐ (0) | 2023.04.10 |
โฌ [Programmers] [Python] [Level2] ์ฃผ์๊ฐ๊ฒฉ (0) | 2023.04.10 |