Does this question require a set or a ordered set?


  • 0
    W

    I guess I've used a bit different recursive thought, and generated a result with a bit different order, cannot pass.
    Shouldn't set be orderless?
    here is my code, it looks a bit ugly though

    public class Solution {
    public List<String> generateParenthesis(int n) {
        if (n == 0)
            return new ArrayList<String>();
        else
            return gen(n);
    }
    
    public ArrayList<String> gen(int n) {
        if (n == 1) {
            ArrayList<String> res = new ArrayList<String>();
            res.add("()");
            return res;
        }
        if (n == 2) {
            ArrayList<String> res = new ArrayList<String>();
            res.add("()()");
            res.add("(())");
            return res;
        }
        ArrayList<String> tmp = gen(n - 1);
        ArrayList<String> res = new ArrayList<String>();
        String first = "";
        for (int i = 0; i < n - 1; i++) {
            first = first + "()";
        }
        
        for (String s : tmp) {
            if (s.equals(first)) {
                res.add(s + "()");
                res.add("(" + s + ")");
            }
            else {
                res.add("()" + s);
                res.add(s + "()");
                res.add("(" + s + ")");
            }
        }
        return res;
    }
    

    }


  • 0
    S

    my solution is just as yours. I think this one is much easier to understand.:( but can't pass the test.....


  • 0
    W

    I still didn't get the idea why it didn't pass


  • 0
    Y

    I was thinking of the same problem. i used DP and the result is correct, but the order is different from the expected output. I think Leetcode should find a way to ignore these differences.


Log in to reply
 

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