标签:leetcode
https://oj.leetcode.com/problems/generate-parentheses/
http://fisherlei.blogspot.com/2012/12/leetcode-generate-parentheses.html
public class Solution { public List<String> generateParenthesis(int n) { // Solution B: // return generateParenthesis_BruteForce(n); // Solution A: return generateParenthesis_Dynamic(n); } //////////////////////////////////////// // Solution A: Dynamic // public List<String> generateParenthesis_Dynamic(int n) { List<String> result = new ArrayList<>(); generate(n, 0, 0, "", result); return result; } private void generate(int n, int left, int right, String s, List<String> result) { if (right > left) return; // ) cannot be more than ( if (left == n && right == n) { // A valid result. result.add(s); return; } if (left == n) // right ‘)‘ is less than n { generate(n, left, right + 1, s + ")", result); return; } generate(n, left + 1, right, s + "(", result); // Add ( generate(n, left, right + 1, s + ")", result); // Add ) } //////////////////////////////////////// // Solution A: Brute Force // public List<String> generateParenthesis_BruteForce(int n) { if (n < 0) return null; // Invalid input if (n == 0) return Collections.<String> emptyList(); List<Set<String>> results = new ArrayList<>(n); results.add(Collections.<String> singleton("()")); // Result for 1; for (int i = 1 ; i < n ; i ++) { Set<String> curR = new HashSet<>(); Set<String> lastR = results.get(i - 1); for (String s : lastR) { // Add one more ‘(‘ in the begining; s = "(" + s; // Iterate s, Add ‘)‘ after each ‘(‘ for (int j = 0 ; j < s.length() ; j ++) { if (s.charAt(j) == ‘(‘) { String newStr = s.substring(0, j + 1) + ")" + s.substring(j + 1, s.length()); curR.add(newStr); } } } results.add(curR); } return new ArrayList<>(results.get(n - 1)); } }
[LeetCode]22 Generate Parentheses
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598421