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的更多相关文章

  1. 【JAVA、C++】LeetCode 020 Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  2. 【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 ...

  3. 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  4. 【JAVA、C++】LeetCode 010 Regular Expression Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  5. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  6. 【JAVA、C++】LeetCode 007 Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...

  7. 【JAVA、C++】LeetCode 006 ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  8. 【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 ...

  9. 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

随机推荐

  1. USACO 3.2 msquare 裸BFS

    又是个裸BFS... 和西安网赛那道1006一样的,只不过加上了要记录方案.顺便复习map 记录方案直接在bfs队列的结点里加一个vector<int> opt,把从开头一直到当前结点的操 ...

  2. Codevs2157 配对

    题目描述 Description 给出2个序列A={a[1],a[2],…,a[n]},B={b[1],b[2],…,b[n]},从A.B中各选出n个元素进行一一配对(可以不按照原来在序列中的顺序), ...

  3. hiho1015(kmp+统计出现次数)

    http://hihocoder.com/problemset/problem/1015 时隔多天再次温习了一下KMP #include <iostream> #include <c ...

  4. Eclipse在线安装ADT插件

    要想使用Eclipse开发Android应用,首先要安装一个ADT插件,在此记录一下在Eclipse中采用在线安装的方式ADT插件,我使用的Eclipse版本是:eclipse-jee-luna-SR ...

  5. 初学JDBC,调用存储过程

    在JDBC简单封装的基础上实现 public class UserDao{ public static void testGetUser(String userName) throws Excepti ...

  6. 升级centos6.5系统的gcc为4.8.5的简易步骤

    Centos6.5_64位升级gcc为4.8.2的简易步骤 一.安装依赖包 yum install texinfo-tex flex zip mpfr-devel libgcc.i686 glibc- ...

  7. ThinkPHP3.2 行为扩展以及插件机制介绍!

    首先行为扩展这个概念是TP架构的核心组成之一,关于行为的解释我就粗略的概括一下吧:TP在从接受到HTTP请求到最终将视图输出,期间经历的很多步骤,这些步骤大家可以在http://document.th ...

  8. python多线程备份MYSQL数据库并删除旧的备份。

    #!/usr/bin/python # -*- coding=utf-8 -*- import time import os import datetime import threading from ...

  9. 一个简单例子:贫血模型or领域模型

    转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...

  10. [Angularjs]ng-file-upload上传文件

    写在前面 最近在弄文档库的H5版,就查找了下相关的上传组件,发现了ng-upload的东东,推荐给大家. 系列文章 [Angularjs]ng-select和ng-options [Angularjs ...