My simple backtracking java solution


  • 0
    X
    public class Solution {
        static List<String> res1;
    	public void generateParenthesisRec(String s, int numLeft, int numRight){
    		if(numLeft == 0 && numRight == 0){
    			res1.add(s);
    		}else{
    			if(numLeft == numRight){
    				generateParenthesisRec(String.valueOf(s)+"(", numLeft-1, numRight);
    			}else if(numLeft < numRight){
    				if(numLeft > 0){
    					generateParenthesisRec(String.valueOf(s)+"(", numLeft-1, numRight);
    				}
    				generateParenthesisRec(String.valueOf(s)+")", numLeft, numRight-1);
    			}
    		}
    	}
    	
        public List<String> generateParenthesis(int n) {
            res1 = new LinkedList<String>();
    		generateParenthesisRec("", n, n);
    		return res1;
        }
    }

Log in to reply
 

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