Is this code valid?


  • 0
    S

    This code is currently failing because it does not match up the order the list returned.
    Is there any other problems with this code, I know this is not dp but just a recursion.

    public class Solution {
        public List<String> generateParenthesis(int n) {
            return dp(n);
            
        }
        
        public List<String> dp(int n) {
            List<String> answer = new ArrayList<>();
            if(n == 0) return answer;
            if(n == 1) {
                answer.add("()");
                return answer;
            }
            List<String> previous = dp(n-1);
            HashMap<String, Integer> map = new HashMap<>(n);
            for(String s : previous) {
                String left = "()" + s;
                if(map.get(left) == null){
                    map.put(left, 1);
                    answer.add(left);
                }
                String mid = "(" + s + ")";
                if(map.get(mid) == null){
                    map.put(mid, 1);
                    answer.add(mid);
                }
                String right = s + "()";
                if(map.get(right) == null){
                    map.put(right, 1);
                    answer.add(right);
                }
            }
            return answer;
            
        }
    }

Log in to reply
 

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