Created
April 20, 2019 02:01
-
-
Save kcdragon/100e875129a6ceb6c0a97bf55272c9d2 to your computer and use it in GitHub Desktop.
leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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