neetcode-gh / leetcode

Leetcode solutions
MIT License
5.55k stars 2.29k forks source link

[Bug] 22. Generate Parentheses returns 'Wrong Answer' despite passing test cases in Leetcode #3485

Open njxue opened 4 months ago

njxue commented 4 months ago
Input: n = 3
Expected Output: ["((()))","(()())","(())()","()(())","()()()"]

It flags the output ["()()()","()(())","(())()","(()())","((()))"] as incorrect. The order of the generated parantheses should not matter.

For reference, this was the code (in Java) that generated the failed test case:

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> parantheses = new ArrayList<>();
        helper(n, n, "", parantheses);
        return parantheses;
    }

    public void helper(int numOpenRemaining, int numCloseRemaining, String p, List<String> parantheses) {
        if (numOpenRemaining == 0 && numCloseRemaining == 0) {
            parantheses.add(p);
            return;
        }
        if (numOpenRemaining < numCloseRemaining) {
            helper(numOpenRemaining, numCloseRemaining - 1, p + ")", parantheses);
        }
        if (numOpenRemaining > 0) {
            helper(numOpenRemaining - 1, numCloseRemaining, p + "(", parantheses);
        }
    }
}