zoukankan      html  css  js  c++  java
  • 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));
        }
    
    }
  • 相关阅读:
    常用连链接命令行存储小工具
    switch case 跳转表
    抖音越狱版本App下载
    AutoLayout + UILabel布局
    ReplayKit2 有线投屏项目-反向Socket实现
    ReplayKit2 有线投屏项目总结
    直播相关-搭建直播流服务器nodejs
    难过!失眠!
    CAShapeLayer
    WebService相关概念介绍
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12192809.html
Copyright © 2011-2022 走看看