Skip to content

Commit da9f37f

Browse files
authored
[Chanz] WEEK 03 Solutions (#2728)
* Add palindrome checking method in Solution class Implement a method to check if a string is a palindrome, ignoring non-alphanumeric characters and case. * Add hammingWeight method to count 1 bits Implement Hamming weight calculation using bit manipulation. * Add combinationSum method to Solution class Implement combination sum algorithm to find all unique combinations of candidates that sum to the target.
1 parent eaffc92 commit da9f37f

3 files changed

Lines changed: 54 additions & 0 deletions

File tree

โ€Žcombination-sum/Chanz82.pyโ€Ž

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3+
4+
result = []
5+
combination = []
6+
def find_target(start, combination, target):
7+
8+
if target == 0 : # ์กฐํ•ฉ ์ƒ์„ฑ ์™„๋ฃŒ.
9+
result.append(combination.copy()) # pop ๋•Œ๋ฌธ์— ๋ณต์‚ฌํ•ด์„œ appendํ•ด์•ผ ํ•จ.
10+
return
11+
12+
elif target < 0 or start >= len(candidates):
13+
return
14+
15+
combination.append(candidates[start])
16+
find_target(start, combination, target-candidates[start]) # ํ˜„์žฌ ์›์†Œ๋ฅผ ๋” ๋ฝ‘๋Š” ๊ฒฝ์šฐ
17+
combination.pop() # ํ˜„์žฌ ์›์†Œ๋Š” ๋‹ค์‹œ ์กฐํ•ฉ์—์„œ ์ œ๊ฑฐ ํ›„, ๋‹ค์Œ ์›์†Œ๋ฅผ ๋ฝ‘์Œ
18+
find_target(start+1, combination, target) # ๋‹ค์Œ ์›์†Œ๋ฅผ ๋ฝ‘๋Š” ๊ฒฝ์šฐ
19+
20+
find_target(0, combination, target)
21+
22+
return result
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
4+
# ๊ณต๊ฐ„๋ณต์žก๋„ : ๋ณ€์ˆ˜ 2๊ฐœ ๋ฐ ์ƒ์ˆ˜๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, O(1)
5+
# ์‹œ๊ฐ„๋ณต์žก๋„ : bit countingํ•œ ์ดํ›„์— n์„ 1/2ํ•˜๋ฏ€๋กœ O(logn)
6+
bit_count = 0
7+
while n > 0:
8+
if n % 2 == 1:
9+
bit_count += 1
10+
n //= 2
11+
12+
return bit_count
13+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def isPalindrome(self, s: str) -> bool:
3+
4+
# ๊ณต๊ฐ„ ๋ณต์žก๋„ : ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋งŒํผ๋งŒ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ O(n)
5+
# ์‹œ๊ฐ„ ๋ณต์žก๋„ : ๋ฌธ์ž์—ด์˜ ๊ธธ์ด ๋งŒํผ ์ˆœํšŒ๋ฅผ 1๋ฒˆ ํ•˜๊ณ , ์ดํ›„์— ํ•œ๋ฒˆ ๋” ์ˆœํšŒ๋ฅผ ํ•˜๋‚˜ ๊ธธ์ด์˜ 1/2 ๊นŒ์ง€๋งŒ ์ˆœํšŒ๋ฅผ ํ•ฉ๋‹ˆ๋‹ค. O(n)
6+
alpha_num_str = ""
7+
for ch in s:
8+
if ch.isalnum():
9+
alpha_num_str += ch.lower()
10+
11+
end_idx = len(alpha_num_str) - 1
12+
for idx, ch in enumerate(alpha_num_str):
13+
if idx >= end_idx:
14+
return True
15+
if ch != alpha_num_str[end_idx]:
16+
return False
17+
end_idx -= 1
18+
return True
19+

0 commit comments

Comments
ย (0)