diff --git a/combination-sum/prograsshopper.py b/combination-sum/prograsshopper.py new file mode 100644 index 0000000000..93a024104f --- /dev/null +++ b/combination-sum/prograsshopper.py @@ -0,0 +1,17 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + # Time complexity: O(n ^ (T / m)) + result = [] + + def dfs(remain_sum, index, path): + if remain_sum < 0: + return + if remain_sum == 0: + result.append(path) + return + + for i in range(index, len(candidates)): + dfs(remain_sum - candidates[i], i, path + [candidates[i]]) + + dfs(target, 0, []) + return result diff --git a/decode-ways/prograsshopper.py b/decode-ways/prograsshopper.py new file mode 100644 index 0000000000..52e5df142c --- /dev/null +++ b/decode-ways/prograsshopper.py @@ -0,0 +1,19 @@ +class Solution: + def numDecodings(self, s: str) -> int: + # sol 1: Time complexity O(n) + dp = {len(s): 1} + + def dfs(start): + if start in dp: + return dp[start] + if s[start] == "0": + return 0 + result = None + if start + 1 < len(s) and int(s[start:start+2]) < 27: + result = dfs(start+1) + dfs(start+2) + else: + result = dfs(start+1) + dp[start] = result + return result + + return dfs(0) diff --git a/number-of-1-bits/prograsshopper.py b/number-of-1-bits/prograsshopper.py new file mode 100644 index 0000000000..15c91c71b1 --- /dev/null +++ b/number-of-1-bits/prograsshopper.py @@ -0,0 +1,10 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + # Time complexity: O(log n) + output = 1 + while n > 1: + remain = n % 2 + n = n // 2 + if remain == 1: + output += 1 + return output diff --git a/valid-palindrome/prograsshopper.py b/valid-palindrome/prograsshopper.py new file mode 100644 index 0000000000..05d7b92cf2 --- /dev/null +++ b/valid-palindrome/prograsshopper.py @@ -0,0 +1,18 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + formatted_string = "".join(elem.lower() for elem in s if elem.isalnum()) + + # sol 1 + # Time complexity: O(n) + return formatted_string == formatted_string[::-1] + + # sol 2 + # Time complexity: O(n) + left = 0 + right = len(formatted_string) - 1 + while left < right: + if formatted_string[left] != formatted_string[right]: + return False + left += 1 + right -= 1 + return True