Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
022.generate_parentheses (Medium)
links:
Title: https://oj.leetcode.com/problems/generate-parentheses/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Produces all valid strings with n-brackets.
Analysis:
- Using DFS can be done quickly, can add ' (' Add ' (', can add ') ' Add ') '. (The following C + + implementation)
- There is also a very witty way to write a short DFS. (Java Implementation)
- For DFS can be memory, with space to change time. (Python Implementation)
Code:
C++:
Class Solution {private:string tmp;void dfs (vector<string> &v, int pos, int n, int used) {if (pos = = n * 2) {Cou T << tmp << endl;v.push_back (TMP); return;} if (used < n) {tmp.push_back (' (');d FS (V, POS + 1, N, used + 1); Tmp.pop_back ();} if (used * 2 > POS) {tmp.push_back (') ');d FS (V, POS + 1, n, used); Tmp.pop_back ();}} Public: vector<string> generateparenthesis (int n) {vector<string> res;if (n = = 0) return res;tmp = "";d FS (res, 0, N, 0); return res; }};
Java:
public class Solution {public list<string> generateparenthesis (int n) { list<string> ret = new Array List<string> (), inner, outter; if (n = = 0) { ret.add (""); return ret; } if (n = = 1) { Ret.add ("()"); return ret; } for (int i = 0; i < n; ++i) { inner = generateparenthesis (i); Outter = Generateparenthesis (N-i-1); for (int j = 0, J < inner.size (); ++j) {for (int k = 0; k < outter.size (); ++k) { Ret.add ("(" + inner.get (j) + ")" + Outter.get (k)); }} return ret; }}
Python:
Class solution: # @param an integer # @return A list of the string def generateparenthesis (self, N): DP = {0: [""], 1: ["()"]} def memorial_dfs (n): if n not in DP: dp[n] = [] for I in range (n): for inner in Memor Ial_dfs (i): for outter in Memorial_dfs (N-i-1): dp[n].append (' (' + inner + ') ' + outter ') return DP[N]
return Memorial_dfs (N)
[Leetcode] 022. Generate parentheses (Medium) (C++/python)