Skip to content

Commit 0414281

Browse files
Merge pull request #1810 from prograsshopper/main
[prograsshopper] Week 3 solution
2 parents 2c40c3a + d745086 commit 0414281

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

combination-sum/prograsshopper.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3+
# Time complexity: O(n ^ (T / m))
4+
result = []
5+
6+
def dfs(remain_sum, index, path):
7+
if remain_sum < 0:
8+
return
9+
if remain_sum == 0:
10+
result.append(path)
11+
return
12+
13+
for i in range(index, len(candidates)):
14+
dfs(remain_sum - candidates[i], i, path + [candidates[i]])
15+
16+
dfs(target, 0, [])
17+
return result

decode-ways/prograsshopper.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def numDecodings(self, s: str) -> int:
3+
# sol 1: Time complexity O(n)
4+
dp = {len(s): 1}
5+
6+
def dfs(start):
7+
if start in dp:
8+
return dp[start]
9+
if s[start] == "0":
10+
return 0
11+
result = None
12+
if start + 1 < len(s) and int(s[start:start+2]) < 27:
13+
result = dfs(start+1) + dfs(start+2)
14+
else:
15+
result = dfs(start+1)
16+
dp[start] = result
17+
return result
18+
19+
return dfs(0)

number-of-1-bits/prograsshopper.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
# Time complexity: O(log n)
4+
output = 1
5+
while n > 1:
6+
remain = n % 2
7+
n = n // 2
8+
if remain == 1:
9+
output += 1
10+
return output

valid-palindrome/prograsshopper.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def isPalindrome(self, s: str) -> bool:
3+
formatted_string = "".join(elem.lower() for elem in s if elem.isalnum())
4+
5+
# sol 1
6+
# Time complexity: O(n)
7+
return formatted_string == formatted_string[::-1]
8+
9+
# sol 2
10+
# Time complexity: O(n)
11+
left = 0
12+
right = len(formatted_string) - 1
13+
while left < right:
14+
if formatted_string[left] != formatted_string[right]:
15+
return False
16+
left += 1
17+
right -= 1
18+
return True

0 commit comments

Comments
 (0)