Lc22-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:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
复制代码
import java.util.ArrayList;
import java.util.List;

/*
 * 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:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 */
public class Lc22 {

    /*
     * 
     * 回溯,有几分搜索算法的味道
     * 
     * 建议debug item这个变量 观察他的变化
     * 
     * 這是基本規則
     * 
     * 
     * 左括号个数必须大于右括号的放置个数 才能继续放右括号
     * 
     * 
     * 左括号的个数小于n 才能继续放左括号
     * 
     * 
     * 左括号和右括号满足上述条件的前提下都为n个,添加这个答案
     */

    public static void generate(String item, int left, int right, List res) {
        if (left == 0 && right == 0) {
            res.add(item);
            return;
        }
        if (left > 0) {
            generate(item + "(", left - 1, right, res);
        }
        if (left < right) {
            generate(item + ")", left, right - 1, res);
        }
    }

    public static List<String> generateParenthesis(int n) {
        List res = new ArrayList<>();
        generate("", n, n, res);
        return res;
    }

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

}
复制代码
posted @   小傻孩丶儿  阅读(135)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示