• 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));
        }
    
    }
  • 相关阅读:
    usaco contest
    chapter 2.getting started
    几种常见排序
    [usaco]Programming Contest Problem Types
    回溯实现组合问题
    第二章:循环结构程序设计
    第一章:程序设计入门
    第三章:数组和字符串
    数据库设计(一对一、一对多、多对多)
    linux与windows回车换行符的区别
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12192809.html
Copyright © 2020-2023  润新知