Considering leetcode 1155
This piece of code exceeds the time limit.
class Solution:
def numRollsToTarget(self, dices: int, faces: int, target: int) -> int:
dp = {}
def ways(t, rd):
if t == 0 and rd == 0: return 1
if t <= 0 or rd <= 0: return 0
if dp.get((t,rd)):
return dp[(t,rd)]
dp[(t,rd)] = sum(ways(t-i, rd-1) for i in range(1,faces+1))
return dp[(t,rd)]
return ways(target, dices) % (10**9 + 7)
While this does not:
class Solution:
def numRollsToTarget(self, dices: int, faces: int, target: int) -> int:
dp = {}
def ways(t, rd):
if t == 0 and rd == 0: return 1
if t <= 0 or rd <= 0: return 0
if (t,rd) in dp:
return dp[(t,rd)]
dp[(t,rd)] = sum(ways(t-i, rd-1) for i in range(1,faces+1))
return dp[(t,rd)]
return ways(target, dices) % (10**9 + 7)
Only difference is dp.get(tuple) vs tuple in dp. AFAIK, both operations are O(1) in terms of time complexity. What is causing the difference here.
One reason i can think of is that in case of dp.get() call, if there is lot of hash conflicts, it might have to internally traverse the linked list to get the None. But i am not sure how in call will avoid that linked list traversal either.
Any way to debug?
[Edit]
To confirm, tuple is not causing any problem, I converted tuple to "-" separated string also. Still the same behaviour.