Why res = res*2*(2*i-1)/(i+1) works, res *= 2*(2*i-1)/(i+1) does not work?


  • 0
    C

    The following code works, while I change to the second fomular it does not work

    def numTrees(self, n):
        res = 1
        for i in xrange(1, n+1):
            res = res*2*(2*i-1)/(i+1)   # Works
        return res
    
    def numTrees(self, n):
        res = 1
        for i in xrange(1, n+1):
            res *= 2*(2*i-1)/(i+1)    # Does not work
        return res

  • 2
    R

    For example,
    res = 5

    res = 5*1/2 -> res = 2

    res *= 1/2 -> res = 0


  • 0

    Just a suggestion: The if n == 0: return 1 is unnecessary, you can remove it.


  • 0
    C

    Yes, you are correct.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.