Skip to content

Instantly share code, notes, and snippets.

@kcdragon
Created April 20, 2019 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcdragon/100e875129a6ceb6c0a97bf55272c9d2 to your computer and use it in GitHub Desktop.
Save kcdragon/100e875129a6ceb6c0a97bf55272c9d2 to your computer and use it in GitHub Desktop.
leetcode
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# dynamic programming
products = []
memo = {}
for i in range(0, len(nums)):
product = 1
leftProduct = self.productBetween(nums, memo, 0, i - 1)
rightProduct = self.productBetween(nums, memo, i + 1, len(nums) - 1)
product = leftProduct * rightProduct
#for j in range(0, len(nums)):
# if i != j:
# product = product * nums[j]
products.append(product)
return products
def productBetween(self, nums, memo, start, end):
# change memo key to tuple
if [start, end] in memo:
return memo[[start, end]]
elif start < 0 or end >= len(nums):
return 1
elif start == end:
return nums[start]
else:
product = nums[start] * self.productBetween(nums, memo, start + 1, end)
memo[[start, end]] = product
return product
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment