DFS in java to solve this problem


  • 0
    J

    The code is starting with "(" and the variable left and right to record the number of "(" and ")" respectively.

    '''
    public class Solution {

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        if(n == 0)  return result;
        String str = "(";
        int left = 1;
        int right = 0;
        searchParenthesis(left,right,str,n,result);
        return result;
    }
    public void searchParenthesis(int left, int right, String str, int n, List<String> result) {
        if(left > n || right > n || right > left)  return;
        if(left == n && right == n) {
            if(!result.contains(str)) {
                result.add(str);
            }
            return;
        }
        searchParenthesis(left+1,right,str+"(",n,result);
        searchParenthesis(left,right+1,str+")",n,result);
    }
    

    }
    '''


Log in to reply
 

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