Generate Parentheses

dfs 的一个关键是termination condition

public class Solution {

    public ArrayList<String> generateParenthesis(int n) {

        ArrayList<String> res = new ArrayList<String>();

        if(n<1) return res;

        dfs(n,n,res,new String());

        return res;

    }

    private void dfs(int nl, int nr,ArrayList<String> res, String item){

        if(nr<nl) return; // nr>nl not working!!!

        if(nr==0 && nl==0) res.add(item);

        

        if(nl>0)

            dfs(nl-1, nr, res, item+'(');

        if(nr>0)

            dfs(nl, nr-1, res, item+')');

    }

}

 

你可能感兴趣的:(r)