diff --git a/combination-sum/i-mprovising.py b/combination-sum/i-mprovising.py new file mode 100644 index 000000000..e1f4adbab --- /dev/null +++ b/combination-sum/i-mprovising.py @@ -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] diff --git a/decode-ways/i-mprovising.py b/decode-ways/i-mprovising.py new file mode 100644 index 000000000..4e4d694c3 --- /dev/null +++ b/decode-ways/i-mprovising.py @@ -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] diff --git a/maximum-subarray/i-mprovising.py b/maximum-subarray/i-mprovising.py new file mode 100644 index 000000000..1e9cfeb2c --- /dev/null +++ b/maximum-subarray/i-mprovising.py @@ -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) diff --git a/number-of-1-bits/i-mprovising.py b/number-of-1-bits/i-mprovising.py new file mode 100644 index 000000000..9494d565d --- /dev/null +++ b/number-of-1-bits/i-mprovising.py @@ -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') diff --git a/valid-palindrome/i-mprovising.py b/valid-palindrome/i-mprovising.py new file mode 100644 index 000000000..bc33565e7 --- /dev/null +++ b/valid-palindrome/i-mprovising.py @@ -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