|
| 1 | +#์ด ๋ฌธ์ ๋ 1)ํ์ฌ ํฉ์ด target๊ณผ ๊ฐ์ผ๋ฉด ๊ฒฐ๊ณผ์ ์ถ๊ฐ ํ ๋๋์๊ฐ, 2) ํ์ฌ ํฉ์ด target์ ์ด๊ณผํ๋ฉด ๋ ์ด์ ์งํํ์ง ์๊ณ ๋๋์๊ฐ, |
| 2 | +#3) ๊ฐ candidate์ ๋ํด recursiveํ๊ฒ ์๋ |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def combinationSum(self, candidates: List[int], target: int): |
| 6 | + #๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฆฌ์คํธ |
| 7 | + result = [] |
| 8 | + |
| 9 | + #start: ํ์ฌ ์ ํํ ์ ์๋ candidate์ ์์ ์ธ๋ฑ์ค |
| 10 | + #current: ํ์ฌ๊น์ง ์ ํํ ์ซ์๋ค์ ๋ฆฌ์คํธ |
| 11 | + #current_sum: ํ์ฌ๊น์ง ์ ํํ ์ซ์๋ค์ ํฉ |
| 12 | + def backtrack(start, current, current_sum): |
| 13 | + #ํ์ฌ ํฉ์ด target๊ณผ ๊ฐ์ผ๋ฉด ํ์ฌ ์กฐํฉ์ ๊ฒฐ๊ณผ์ ์ถ๊ฐ ํ ๋๋์๊ฐ |
| 14 | + if current_sum == target: |
| 15 | + result.append(current.copy()) |
| 16 | + return |
| 17 | + #ํ์ฌ ํฉ์ด target์ ์ด๊ณผํ๋ฉด ๋ ์ด์ ์งํํ์ง ์๊ณ ๋๋์๊ฐ |
| 18 | + if current_sum > target: |
| 19 | + return |
| 20 | + |
| 21 | + #start ํ๋ผ๋ฏธํฐ๋ฅผ ์ฌ์ฉํ์ฌ ์ค๋ณต ์กฐํฉ์ด ์๊ธฐ์ง ์๋๋ก ์ด์ ์ ์ ํํ ์ซ์๋ถํฐ ๋ค์ ์์ |
| 22 | + for i in range(start, len(candidates)): |
| 23 | + #ํ์ฌ candidate ์ ํ |
| 24 | + current.append(candidates[i]) |
| 25 | + #recursive ํธ์ถ : i๋ฅผ ๊ทธ๋๋ก ์ ๋ฌํ์ฌ ๊ฐ์ ์ซ์๋ฅผ ๋ฌดํ๋ฐ๋ณตํ์ฌ ์ฌ์ฉํ ์ ์์. |
| 26 | + backtrack(i, current, current_sum + candidates[i]) |
| 27 | + #๋ง์ง๋ง์ ์ ํํ ์ซ์ ์ ๊ฑฐ |
| 28 | + current.pop() |
| 29 | + |
| 30 | + #๋ฐฑํธ๋ํน ์์ |
| 31 | + backtrack(0, [], 0) |
| 32 | + #๋ชจ๋ ๊ฐ๋ฅํ ์กฐํฉ ๋ฐํ |
| 33 | + return result |
| 34 | + |
| 35 | + |
| 36 | +# ํ
์คํธ ์ผ์ด์ค |
| 37 | +solution = Solution() |
| 38 | + |
| 39 | +# ํ
์คํธ 1 |
| 40 | +test1_candidates = [2,3,6,7] |
| 41 | +test1_target = 7 |
| 42 | +print(f"Expected: [[2,2,3],[7]]") |
| 43 | +print(f"Result: {solution.combinationSum(test1_candidates, test1_target)}") |
| 44 | + |
| 45 | +# ํ
์คํธ 2 |
| 46 | +test2_candidates = [2,3,5] |
| 47 | +test2_target = 8 |
| 48 | +print(f"Expected: [[2,2,2,2],[2,3,3],[3,5]]") |
| 49 | +print(f"Result: {solution.combinationSum(test2_candidates, test2_target)}") |
| 50 | + |
| 51 | +# ํ
์คํธ 3 |
| 52 | +test3_candidates = [2] |
| 53 | +test3_target = |
| 54 | +print(f"Expected: []") |
| 55 | +print(f"Result: {solution.combinationSum(test3_candidates, test3_target)}") |
| 56 | + |
| 57 | + |
| 58 | +#์๊ฐ ๋ณต์ก๋: O(2^target) |
| 59 | + #๊ฐ ๋จ๊ณ์์ ์ซ์๋ฅผ ์ ํํ๊ฑฐ๋ ์ ํํ์ง ์๋ ๋ ๊ฐ์ง ์ ํ์ง๊ฐ ์์ |
| 60 | + #์ต์
์ ๊ฒฝ์ฐ, target์ ๋ง๋ค๊ธฐ ์ํด ๋ชจ๋ ๊ฐ๋ฅํ ์กฐํฉ์ ์๋ํด์ผ ํจ. |
| 61 | + #์๋ฅผ ๋ค์ด candidates = [1], target = 10์ผ ๋: |
| 62 | + #[1,1,1,1,1,1,1,1,1,1]๊น์ง ์๋ํด์ผ ํจ |
| 63 | + #์ด๋ 2^10์ ๊ฐ๊น์ด ๊ฒฝ์ฐ์ ์๊ฐ ๋ฐ์ |
| 64 | +#๊ณต๊ฐ ๋ณต์ก๋: O(target) |
| 65 | + #๊ฐ ์ฌ๊ท ํธ์ถ๋ง๋ค ์๋ก์ด ์คํ ํ๋ ์์ด ์์ฑ๋จ |
| 66 | + #์ต๋ ๊น์ด๋ target์ ๊ฐ์ฅ ์์ ์ซ์๋ก ๋๋ ๊ฐ์ |
| 67 | + #์๋ฅผ ๋ค์ด target = 7, ๋ฆฌ์คํธ ๋ด ๊ฐ์ฅ ์์ ์ซ์ = 2์ผ ๋ |
| 68 | + #7/2 = 3.5 โ ์ต๋ 3๋ฒ์ ์ฌ๊ท ํธ์ถ |
| 69 | + #[2,2,3]์ ๋ง๋ค ๋ 3๋ฒ์ ์ฌ๊ท ํธ์ถ |
| 70 | + #๊ณต๊ฐ ๋ณต์ก๋๋ target ๊ฐ์ ๋น๋กํ์ฌ ์ฆ๊ฐํ๋ฏ๋ก O(target)์ |
| 71 | + #์ด๋ target์ด ์ปค์ง์๋ก ๋ ๋ง์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ํ์ํ๋ค๋ ๊ฒ์ ์๋ฏธํจ |
0 commit comments