22. 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:

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

完全想不到,在看了别人的算法后,自己画图加以理解才明白,主要是利用两个条件去限制迭代,把不合格的排除掉,第一个open < max的条件筛选掉的用感叹号表示,第二个条件close < open筛选掉的用X表示。max=3时迭代流程如图:流程图展示的便是回朔法的求解情况,根据题目,求取确切的解空间树通过不断迭代进行求取,在遇到不符合情况的时候中断该操作并返回上一层。要注意的是,回朔法可能因为没有遍历整个解空间树从而导致求解不完善,不过其依然属于暴力搜索的一种,从图中可见其搜索范围呈指数级增长。
迭代流程图

代码如下:

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        helper(res, sb, 0, 0, n);
        return res;
    }
    public void helper(List<String> res, StringBuilder sb, int open, int close, int max){
        if(open == max && close == max){
            res.add(sb.toString());
            return;
        }

        if(open < max){
            sb.append("(");
            helper(res, sb, open+1, close, max);
            sb.setLength(sb.length()-1);
        }
        if(close < open){
            sb.append(")");
            helper(res, sb, open, close+1, max);
            sb.setLength(sb.length()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/timemagician/article/details/79096914