LeetCode之递归

打印n对括号的全部有效组合

题目

https://leetcode.cn/problems/generate-parentheses/submissions/

当n=3时,可能的组合有:(()()), ((())), ()(()), (())(), ()()()

code

package org.example.kuohao;

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

class Solution {
    private StringBuilder path = new StringBuilder();
    List<String> pathList = new ArrayList<>();

    public static void main(String[] args) {
        System.out.println(new Solution().generateParenthesis(2));
    }

    public List<String> generateParenthesis(int n) {
        pathList = new ArrayList<>();
        path = new StringBuilder();
        back(n, n);
        return pathList;
    }

    /**
     * 生成成对的括号
     *
     * @param left 左边剩余的个数
     * @param right 右边剩余的个数
     */
    private void back(int left, int right) {
        if (left == 0 && right == 0) {
            pathList.add(path.toString());
            return;
        }
        if (left > 0) {
            path.append('(');
            back(left - 1, right);
            path.deleteCharAt(path.length() - 1);
        }
        if (left < right && right > 0) {
            path.append(')');
            back(left, right - 1);
            path.deleteCharAt(path.length() - 1);
        }
    }
}

你可能感兴趣的:(#,Java,LeetCode,leetcode,算法,职场和发展)