leetcode practice -Generate Parentheses(DFS)

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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是深度优先搜索,对于有些排列组合,DFS可以在上面发挥作用,因为DFS是探索符合条件的一个解,排列就是要所有适合的解,故用DFS。
我们要从第一个左括号开始衍生,左右,左右,这样。注意条件对左括号,右括号的限制。

class Solution {
	//深度优先算法
	String left="(";
	String right=")";
    public List<String> generateParenthesis(int n) {
        List<String> list=new ArrayList<>();
        int leftcount=1;	//左括号数目
        int rightcount=0;
        String str=left;	//初始是左括号
        BFS(list,str,leftcount,rightcount,n);
        return list;
    }
	private void BFS(List<String> list, String str1, int leftcount, int rightcount, int n) {
		String str=new String(str1);	//继承上一步的字符串
		//三个剪枝操作
		if(leftcount>n)		//左边越界
			return ;
		if(leftcount==rightcount&&leftcount==n)	{//左右括号数相等了
			list.add(str);
			return ;
		}
		if(leftcount<rightcount) //右括号太多了
			return ;
		//加左括号或者右括号
		BFS(list,str+left,leftcount+1,rightcount,n);
		BFS(list,str+right,leftcount,rightcount+1,n);
		
	}
//	public static void main(String[] agrs) { //TEST
		int n=10;
		List<String> list=new Solution().generateParenthesis(n);
		for(String str:list) {
			System.out.println(str);
		}
//	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值