Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions combination-sum/i-mprovising.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
Time complexity O(c*t)
Space complexity O(c*t)
Dynamic programming
"""

class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
# init dp array
dp = [[] for _ in range(target+1)] # dp[i] : combinations to sum to i
dp[0] = [[]]

for candidate in candidates:
for num in range(candidate, target+1):
for comb in dp[num-candidate]:
dp[num].append(comb + [candidate])

return dp[-1]
40 changes: 40 additions & 0 deletions decode-ways/i-mprovising.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
Time complexity O(n)
Space complexity O(1)

Dynamic programming
"""


class Solution:
def numDecodings(self, s: str) -> int:
if s[0] == '0':
return 0
n = len(s)
if n == 1:
return 1
tmp = int(s[:2])
dp = [1, 1]
if 11 <= tmp <= 26:
if tmp != 20:
dp = [1, 2]
elif s[1] == '0':
if tmp not in [10, 20]:
return 0
if n == 2:
return dp[-1]

for i in range(2, n):
if s[i] == '0':
if s[i-1] in ['1', '2']:
cur = dp[0]
else:
return 0
else:
cur = dp[1]
tmp = int(s[i-1:i+1])
if (11 <= tmp <= 26) and (tmp != 20):
cur += dp[0]
dp = [dp[1], cur]

return dp[-1]
18 changes: 18 additions & 0 deletions maximum-subarray/i-mprovising.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
Time complexity O(n)
Space complexity O(n)
Dynamic programming
"""


class Solution:
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
dp = [0 for _ in range(n)]
dp[0] = nums[0]

for i in range(1, n):
dp[i] = max(dp[i-1]+nums[i], nums[i])

return max(dp)
8 changes: 8 additions & 0 deletions number-of-1-bits/i-mprovising.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""
Time complexity O(n)
Space complexity O(1)
"""

class Solution:
def hammingWeight(self, n: int) -> int:
return bin(n).count('1')
13 changes: 13 additions & 0 deletions valid-palindrome/i-mprovising.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""
Time complexity O(n)
Space complexity O(n)
"""

class Solution:
def isPalindrome(self, s: str) -> bool:
# preprocessing
string = [c for c in s.lower() if c.isalnum()]

if string == [c for c in string[::-1]]:
return True
return False