Skip to content

Instantly share code, notes, and snippets.

@thmain
Created February 24, 2016 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/dc9b89e357e1f8ffbf85 to your computer and use it in GitHub Desktop.
Save thmain/dc9b89e357e1f8ffbf85 to your computer and use it in GitHub Desktop.
public class PrintValidParentheses {
public static void Validparentheses(int openP, int closeP, String string) {
if (openP == 0 && closeP == 0) // mean all opening and closing in
// string,
// print it
System.out.println(string);
if (openP > closeP) // means closing parentheses is more than open ones
return;
if (openP > 0)
Validparentheses(openP - 1, closeP, string + "("); // put ( and
// reduce
// the count by
// 1
if (closeP > 0)
Validparentheses(openP, closeP - 1, string + ")"); // put ) and
// reduce
// the count by
// 1
}
public static void printParentheses(int n) {
Validparentheses(n / 2, n / 2, "");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 4;
printParentheses(n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment