classSolution{ List<String> res = null; public List<String> generateParenthesis(int n){ res = new ArrayList<>(); char [] Parenthesis = newchar[2*n]; for (int i = 0; i < Parenthesis.length; i++) { Parenthesis[i]='('; } dfs(Parenthesis,1,0); return res; }
voiddfs(char[] Parenthesis,int index,int count){ if (count==Parenthesis.length/2) { res.add(String.valueOf(Parenthesis)); return; }
for (int i = index; i < Parenthesis.length; i++) { if (i+1<(count+1)*2) continue; Parenthesis[i] = ')'; dfs(Parenthesis,i+1,count+1); Parenthesis[i]='('; } } }
/** * 困难级别,以后需要回看一下 */ publicclasslongestValidParentheses{ //动态规划 publicintLongestValidParentheses(String s){ int maxans = 0; int []dp = newint[s.length()]; for (int i = 1; i < dp.length; i++) { if (s.charAt(i)==')') {
//使用栈的方法进行 publicintLongestValidParentheses2(String s){ int maxans = 0; //将下标存进去 Stack<Integer> stack = new Stack<>(); stack.push(-1); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); if (stack.empty()) { stack.push(i); } else { maxans = Math.max(maxans, i - stack.peek()); } } } return maxans; }
//贪心算法 publicintlongestValidParentheses3(String s){ int left = 0, right = 0, maxlength = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * right); } elseif (right > left) { left = right = 0; } } left = right = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '(') { left++; } else { right++; } if (left == right) { maxlength = Math.max(maxlength, 2 * left); } elseif (left > right) { left = right = 0; } } return maxlength; }
publicstaticvoidmain(String[] args){ longestValidParentheses l = new longestValidParentheses(); String s = "()(())"; System.out.println(l.LongestValidParentheses(s)); } }