首页 > 编程语言 > 详细

LeetCode算法笔记(二)

时间:2020-04-08 16:54:20      阅读:46      评论:0      收藏:0      [点我收藏+]

一.括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 = 3,生成结果为:

技术分享图片 

暴力法:采用递归的方法罗列出所有的组合,然后进行判断
class
Solution { public List<String> generateParenthesis(int n) { List<String> combinations = new ArrayList<String>(); char[] current = new char[2*n]; generateAll(current, 0, combinations); return combinations; } public void generateAll(char[] current, int pos, List<String> result){ if(current.length == pos){ System.out.println(current); if(valid(current)){ result.add(new String(current)); } }else{ current[pos] = ‘(‘; generateAll(current, pos+1, result); current[pos] = ‘)‘; generateAll(current, pos+1, result); } } public boolean valid(char[] current){ int balance = 0; for(int i = 0; i < current.length; i++){ if(current[i] == ‘(‘){ balance++; }else{ balance--; } if(balance < 0) return false; } return (balance == 0); } }
回溯法:只有在我们知道序列仍然保持有效时才添加 ‘(‘ or ‘)‘,而不是像 方法一 那样每次添加。我们可以通过跟踪到目前为止放置的左括号和右括号的数目来做到这一点,
如果我们还剩一个位置,我们可以开始放一个左括号。 如果它不超过左括号的数量,我们可以放一个右括号。
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        generateAll(result, "", 0, 0, n);
        return result;
    }
    public void generateAll(List<String> result, String ans, int open, int close, int max){
        if(close + open == 2*max){
            result.add(ans);
            return;
        }
        if(open < max)
            generateAll(result, ans + "(", open+1, close, max);
        if(close < open)
            generateAll(result, ans + ")", open, close+1, max);
    }
}

 

 
 

二.

 

LeetCode算法笔记(二)

原文:https://www.cnblogs.com/ifreewolf/p/12660244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!