1. 程式人生 > >22-generate-parentheses

22-generate-parentheses

題目描述:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

題目解答:

package com.jack.algorithm;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * create by jack 2018/11/2
 *
 * @author jack
 * @date: 2018/11/2 23:30
 * @Description:
 * 給n對括號,查詢所有正確組合的括號
 */
public class GenerateParentheses {

    /**
     * 題目描述:
     * https://leetcode.com/problems/generate-parentheses/
     * @param n
     * @return
     */
    public static List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
        if (n == 0) {
            ans.add("");
        } else {
            for (int c = 0; c < n; ++c)
                for (String left: generateParenthesis(c))
                    for (String right: generateParenthesis(n-1-c))
                        ans.add("(" + left + ")" + right);
        }
        return ans;
    }

    public static void main(String[] args) {
        int n = 3;
        List<String> list = generateParenthesis(n);
        System.out.println("list="+ JSONObject.toJSONString(list));
    }
}

原始碼地址:

原始碼

總結:程式碼既然能如此整潔簡單,這需要看透本質,進行抽象出中心思想