【JAVA、C++】LeetCode 022 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
解题思路一:
通过观察n=2和n=3的情况可以知道,只要在n=2的String 开头、末尾、'(' 插入“()”即可,注意防止重复。
JAVA实现如下:
static public List<String> generateParenthesis(int n) {
HashSet<String> set = new HashSet<String>();
if (n == 1)
set.add("()");
if (n > 1) {
ArrayList<String> lastList = new ArrayList<String>(
generateParenthesis(n - 1));
StringBuilder sb = new StringBuilder();
for (String string : lastList) {
sb = new StringBuilder(string);
set.add(sb.toString() + "()");
set.add("()" + sb.toString());
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == '(') {
sb.insert(i + 1, "()");
set.add(sb.toString());
}
sb = new StringBuilder(string);
}
}
}
return new ArrayList<String>(set);
}
解题思路二:
通过观察可以发现,任何符合条件的Parenthesis(n)总是可以分解为(generateParenthesis(k))+generateParenthesis(n-1-k),同时由于后半部分generateParenthesis(n-1-k)的唯一性,这种算法不会产生重复的元素,因此采用DFS进行一次遍历即可,这种算法更高效!JAVA实现如下:
static public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>(), leftList, rightList;
if (n == 0)
list.add("");// 很关键,不能删除
if (n == 1)
list.add("()");
else {
for (int i = 0; i < n; i++) {
leftList = generateParenthesis(i);
rightList = generateParenthesis(n - i - 1);
for (String leftPart:leftList)
for (String rightPart:rightList)
list.add("(" + leftPart + ")" + rightPart);
}
}
return list;
}
C++:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string>res;
if (n == ) {
res.push_back("");
return res;
}
if (n == ) {
res.push_back("()");
return res;
}
for (int i = ; i < n; i++) {
vector<string> left = generateParenthesis(i);
vector<string>right = generateParenthesis(n-i-);
for (string leftPart : left)
for (string rightPart : right)
res.push_back("(" + leftPart + ")" + rightPart);
}
return res;
}
};
【JAVA、C++】LeetCode 022 Generate Parentheses的更多相关文章
- 【JAVA、C++】LeetCode 020 Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 【JAVA、C++】LeetCode 005 Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...
- 【JAVA、C++】LeetCode 002 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- 【JAVA、C++】 LeetCode 008 String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【JAVA、C++】LeetCode 007 Reverse Integer
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...
- 【JAVA、C++】LeetCode 006 ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...
- 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, ...
随机推荐
- 【BZOJ-2843&1180】极地旅行社&OTOCI Link-Cut-Tree
2843: 极地旅行社 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 323 Solved: 218[Submit][Status][Discuss ...
- 【BZOJ-2733】永无乡 Splay+启发式合并
2733: [HNOI2012]永无乡 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 2048 Solved: 1078[Submit][Statu ...
- C#获取局域网中的所有正在使用的IP地址
方法不是很好. using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...
- POJ2387 Til the Cows Come Home(SPFA + dijkstra + BallemFord 模板)
Til the Cows Come Home Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 37662 Accepted ...
- Stream Byte[] 转换
public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(byt ...
- js中数组以及for循环的使用
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> < ...
- ci默认控制器
默认控制器 前面提到,如果在请求中没有指明具体的控制器,CI将会把页面重定向到一个系统默认的页面.这个默认页面可以自己设定,它存放在如下地址:/system/application/config/ro ...
- UILable点击事件
UILabel *lLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 19, 105, 1)]; lLabel.backgroundColor ...
- linux ftp命令(转)
此命令需要安装ftp, yum install ftp 1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 ...
- .NET中使用Memcached的相关资源整理
Memcached官方站点:http://www.danga.com/memcached/ Memcached Win32 1.2.6下载:http://code.jellycan.com/memca ...