Skip to content

Commit fac63f6

Browse files
authored
Merge pull request #1308 from i-mprovising/main
[i-mprovising] Week 03 solutions
2 parents e4d1726 + 83139c1 commit fac63f6

File tree

5 files changed

+98
-0
lines changed

5 files changed

+98
-0
lines changed

combination-sum/i-mprovising.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
Time complexity O(c*t)
3+
Space complexity O(c*t)
4+
5+
Dynamic programming
6+
"""
7+
8+
class Solution:
9+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
10+
# init dp array
11+
dp = [[] for _ in range(target+1)] # dp[i] : combinations to sum to i
12+
dp[0] = [[]]
13+
14+
for candidate in candidates:
15+
for num in range(candidate, target+1):
16+
for comb in dp[num-candidate]:
17+
dp[num].append(comb + [candidate])
18+
19+
return dp[-1]

decode-ways/i-mprovising.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(1)
4+
5+
Dynamic programming
6+
"""
7+
8+
9+
class Solution:
10+
def numDecodings(self, s: str) -> int:
11+
if s[0] == '0':
12+
return 0
13+
n = len(s)
14+
if n == 1:
15+
return 1
16+
tmp = int(s[:2])
17+
dp = [1, 1]
18+
if 11 <= tmp <= 26:
19+
if tmp != 20:
20+
dp = [1, 2]
21+
elif s[1] == '0':
22+
if tmp not in [10, 20]:
23+
return 0
24+
if n == 2:
25+
return dp[-1]
26+
27+
for i in range(2, n):
28+
if s[i] == '0':
29+
if s[i-1] in ['1', '2']:
30+
cur = dp[0]
31+
else:
32+
return 0
33+
else:
34+
cur = dp[1]
35+
tmp = int(s[i-1:i+1])
36+
if (11 <= tmp <= 26) and (tmp != 20):
37+
cur += dp[0]
38+
dp = [dp[1], cur]
39+
40+
return dp[-1]

maximum-subarray/i-mprovising.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(n)
4+
5+
Dynamic programming
6+
"""
7+
8+
9+
class Solution:
10+
def maxSubArray(self, nums: List[int]) -> int:
11+
n = len(nums)
12+
dp = [0 for _ in range(n)]
13+
dp[0] = nums[0]
14+
15+
for i in range(1, n):
16+
dp[i] = max(dp[i-1]+nums[i], nums[i])
17+
18+
return max(dp)

number-of-1-bits/i-mprovising.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(1)
4+
"""
5+
6+
class Solution:
7+
def hammingWeight(self, n: int) -> int:
8+
return bin(n).count('1')

valid-palindrome/i-mprovising.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""
2+
Time complexity O(n)
3+
Space complexity O(n)
4+
"""
5+
6+
class Solution:
7+
def isPalindrome(self, s: str) -> bool:
8+
# preprocessing
9+
string = [c for c in s.lower() if c.isalnum()]
10+
11+
if string == [c for c in string[::-1]]:
12+
return True
13+
return False

0 commit comments

Comments
 (0)