December 02, 2025
์ซ์๋ค์ด ์ฃผ์ด์ง๋ฉด ๊ทธ ์ซ์๋ค์ ํฉ์ด ํ๊ฒ ์ซ์๊ฐ ๋๋ ๋ชจ๋ ์กฐํฉ์ ๋ฐํํ๋ ๋ฌธ์ ๋ค.
์ด ๋ฌธ์ ๋ ๋ฐฑํธ๋ํน(Backtracking) ๊ธฐ๋ฒ์ ์ฌ์ฉํ์ฌ ํด๊ฒฐํ ์ ์์ต๋๋ค. ์ฃผ์ด์ง ์ซ์๋ค๋ก ๋ง๋ค ์ ์๋ ๋ชจ๋ ์กฐํฉ์ ์ฌ๊ท์ ์ผ๋ก ์์ฑํฉ๋๋ค.
ํต์ฌ: ๊ธฐ์ตํด์ผ ํ ์ ๋ณด๋ฅผ ๋ฐฑํธ๋ํน ํจ์์ ์ ๋ฌํ์ฌ ํ๊ฒ๊น์ง ๋๋ฌํ๋ ์กฐํฉ์ ์ฐพ๋ ๊ฒ์ด ์ค์ํ๋ค.
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
def backtrack(idx, curr_comb, curr_sum):
if curr_sum==target:
res.append(curr_comb[:])
return
if idx==len(candidates) or curr_sum > target:
return
backtrack(idx, curr_comb+[candidates[idx]], curr_sum+candidates[idx])
backtrack(idx+1, curr_comb, curr_sum)
backtrack(0,[],0)
return res
O(N^(T/M + 1)) ; N์ candidates์ ๊ธธ์ด, T๋ target, M์ candidates์ ์ต์๊ฐ์
๋๋ค. ์ต์
์ ๊ฒฝ์ฐ, ๊ฐ ์ฌ๊ท ํธ์ถ์์ N๊ฐ์ ์ ํ์ง๊ฐ ์์ผ๋ฉฐ, ์ต๋ ๊น์ด๋ T/M์ด ๋ ์ ์์ต๋๋ค.O(k) ; ์ฌ๊ท ํธ์ถ ์คํ๊ณผ ๋ฐฉ๋ฌธ ์งํฉ์ ์ฌ์ฉ๋๋ ๊ณต๊ฐ์
๋๋ค.Constraints:
1 <= candidates.length <= 30
2 <= candidates[i] <= 40
All elements of candidates are distinct.
1 <= target <= 40