Different answer between local IDLE and LeetCode

  • 0

    I wrote the program in python. When I tested the program in IDLE, for example n=2, I got ['()()', '(())'], however, when I submit the answer to the oj, it said that:

    Input: 2

    Output: ["()","()()","(())"]

    Expected: ["(())","()()"]

    the code are as follow:

    class Solution:
    # @param an integer
    # @return a list of string
    rearr = []
    parentheses = []
    def generateParenthesis(self, n):
        self.parentheses = [' ']*2*n
        self.recursion(n, 0, 0)
        return self.rearr
    def recursion(self, n, i, ord):
        if i == n*2:
            if 0 == ord:
        if ord >= 1:
            self.parentheses[i] = ')'
            self.recursion(n, i+1, ord-1)
        self.parentheses[i] = '('
        self.recursion(n, i+1, ord+1)

    My question is: how could this happen, does it caused by the python version? I use python 2.7

  • 2

    Tried this, and got accepted. But, still no idea why this happens.

    def generateParenthesis(self, n):
        self.parentheses = [' ']*2*n
        self.rearr = []    # Add this line.
        self.recursion(n, 0, 0)
        return self.rearr

  • 8

    You are declaring rearr and parentheses as class static variables. As the judger runs all testcases in one go, you have to declare those variables as class instance variables instead so they are properly initialized for each test case, like this:

    class Solution:
        def __init__(self):
            self.rearr = []
            self.parentheses = []

  • 0

    Thanks, and @1337c0d3r has explained the reason for why.

  • 0

    Thanks for your answer. I got acceped with the code.

  • 1

    Technically it's right. But write the method using the member variable my cause problems.
    I assume your code won't work if you call generateParenthesis two times. Although this won't cause problem in passing the test, it's not the right pass.

Log in to reply

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