Java simple DP solution


  • 0
    D
    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String>[] results = new ArrayList[n+1];
            results[0] = new ArrayList<String>();
            
            List<String> firstResult = new ArrayList<String>();
            firstResult.add("()");
            results[1] = firstResult;
            
            for (int i = 2; i < results.length; i++) {
                results[i] = generateSolution(results[i-1], i-1);
            }
            
            return results[n];
        }
        
        public List<String> generateSolution(List<String> previousSolution, int previousSize) {
            Set<String> uniqueNewSolutions = new HashSet<String>();
            
            for (int i = 0; i < previousSolution.size(); i++) {
                String item = previousSolution.get(i);
                StringBuilder sb = new StringBuilder(item);
                for (int j = 0; j <= previousSize; j++) {
                    sb.insert(j, "()");
                    uniqueNewSolutions.add(sb.toString());
                    sb = new StringBuilder(item);
                }    
            }
            
            List<String> resultToReturn = new ArrayList<String>();
            resultToReturn.addAll(uniqueNewSolutions);
            return resultToReturn;
        }
    }
    

Log in to reply
 

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