合法括號

  • 給一個數字n,給出全部的n個左右括號組成的可用組合:
  • 輸入:2 輸出:(()),()()
  • 遞歸,左括號個數大於右括號能夠繼續增長,若是少於那麼說明組合錯誤,中止遞歸,代碼以下:
public class AddParen {
    public ArrayList<String> genParens(int n){
        ArrayList<String> res = new ArrayList<>();
        char [] str = new char[n*2];
        addParen(res, n, n, str, 0);
        return res;
    }
    public void addParen(ArrayList<String> list, int leftRem, int rightRem, char [] str, int count){
        if(count == str.length) {
            list.add(String.valueOf(str));
        }
        if(leftRem > 0) {
            str[count] = '(';
            addParen(list, leftRem - 1, rightRem, str, count + 1);
        }
        if(rightRem > 0 && rightRem > leftRem) {
            str[count] = ')';
            addParen(list, leftRem, rightRem - 1, str, count + 1);
        }
    }
}
相關文章
相關標籤/搜索