[leetcode] 22.Generate Parentheses
2015-08-18 18:12
288 查看
题目:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题意:
给n对括号,写一个方程去给出所有合法的括号搭配。合法的括号搭配的意思是当右括号出现时,前面必然有与之匹配的左括号。
思路:
这道题目考察的是使用回溯的方法递归求解题目。我们知道n是括号的对数,那么最终的字符串中有2*n个符号,其中n个是’(‘, n个是’)’。所以我们对这2*n个位置进行扫描,查看能存放的符号的所有组合。
1.当所有的’(‘都出现了后,那么接下来的可能就只有剩余的’)’都加到当前字符串的后面这种可能。
当前位置存放下’(‘,继续扫描下一个位置。
如果前面位置的’(‘数大于’)’数,那么这个位置是可以放入’)’。
所以我们在代码中不光要保存当前扫描到的字符串的符号组成,还要保存’(‘与’)’的数目。
以上。
代码如下:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题意:
给n对括号,写一个方程去给出所有合法的括号搭配。合法的括号搭配的意思是当右括号出现时,前面必然有与之匹配的左括号。
思路:
这道题目考察的是使用回溯的方法递归求解题目。我们知道n是括号的对数,那么最终的字符串中有2*n个符号,其中n个是’(‘, n个是’)’。所以我们对这2*n个位置进行扫描,查看能存放的符号的所有组合。
1.当所有的’(‘都出现了后,那么接下来的可能就只有剩余的’)’都加到当前字符串的后面这种可能。
当前位置存放下’(‘,继续扫描下一个位置。
如果前面位置的’(‘数大于’)’数,那么这个位置是可以放入’)’。
所以我们在代码中不光要保存当前扫描到的字符串的符号组成,还要保存’(‘与’)’的数目。
以上。
代码如下:
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> result; if(n == 0)return result; string temp = ""; getAllParenthesis(result, temp, n, 0, 0); return result; } void getAllParenthesis(vector<string>& result, string temp, int &n, int l, int r) { if(l == n) { string s(n - r, ')'); temp += s; result.push_back(temp); return; } temp.push_back('('); getAllParenthesis(result, temp, n, l + 1, r); temp.pop_back(); if( r < l) { temp.push_back(')'); getAllParenthesis(result, temp, n, l, r + 1); temp.pop_back(); } } };
相关文章推荐
- 在android设备上获取内网IP
- IP地址的分类 公有地址和私有地址 子网掩码
- 思科多nat顺序
- Struts2技术详解
- 【读书笔记】iOS-给模拟器相册增加图片
- 【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
- 1869 六度分离【floyd】
- 经典算法---渊子赛马
- JavaWeb中实现删除修改
- mysql自增id归0的方法
- 华为OJ(购物单)
- 用一枚实名戒指来弥补我对你的爱
- Codeforces C The Game of Efil (暴力枚举状态)
- android内置存储器memory和第三方外部存储disk管理
- 折返(Reentrancy)VS线程安全(Thread safety)
- POJ 2393 Yogurt factory
- 全半角空格导致的Sql Server Analysis Services处理错误(转载)
- Handler机制的初步理解
- java中的向上转型和向下转型
- 出现Unable to locate appropriate constructor on class解决方案