Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

All combinations of well-formed parentheses

/*
	This is an implementation that efficiently
	generates all combinations of well-formed 
	parentheses for n pairs of parentheses. 

	Time complexity: O(4^n/sqrt(n)), 
	upperbound of nth Catalan number
	Space complexity: O(4^n/sqrt(n))
*/
import java.util.List;
import java.util.ArrayList;

public class GenerateParentheses {
	public static void main(String[] args) {
		// Below outputs: [((())), (()()), (())(), ()(()), ()()()]
		System.out.println(generateParenthesis(3));
	}
	private static List<String> generateParenthesis(int n) {
		List<String> result = new ArrayList<>();

		createCombinations(n, n, new StringBuilder(), result);

		return result;
	}
	private static void createCombinations(int openingNeeded, int closingNeeded, StringBuilder prefix,
			List<String> result) {
		// Keep track of number of opening and closing symbols added
		// Add a new one only if sequence remains valid.
		if (openingNeeded > 0) {
			prefix.append("(");
			createCombinations(openingNeeded - 1, closingNeeded, prefix, result);
			prefix.deleteCharAt(prefix.length() - 1);
		}

		if (openingNeeded < closingNeeded) {
			prefix.append(")");
			createCombinations(openingNeeded, closingNeeded - 1,
					prefix, result);
			prefix.deleteCharAt(prefix.length() - 1);
		}

		if (closingNeeded == 0) {
			result.add(prefix.toString());
		}
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: swing enter key 
Java :: formartted string java 
Java :: android studio start activity 
Java :: java get distinct values from list 
Java :: display image from database in java servlet 
Java :: How to chage font progrmatically 
Java :: java eliminate numbers from string 
Java :: java pause program until key pressed 
Java :: adding 2 variable in java 
Java :: java instant to localdatetime 
Java :: java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.length()" because "this.text" is null 
Java :: how to add to arras java 
Java :: java code to reverse an integer 
Java :: java program to find perimeter of rectangle 
Java :: minecraft java 
Java :: Copying Arrays Using copyOfRange() method Java 
Java :: how to reset jframe java swing 
Java :: return day from date in java 
Java :: using buidfeatures to enable viewbinding 
Java :: random number between 1 and 100 java 
Java :: test if string is float java 
Java :: java get size of matrix 
Java :: list to array java 
Java :: java factorial loop 
Java :: expected exception junit 
Java :: solid principles in programming 
Java :: highlight selected item in recyclerview android 
Java :: javafx textarea how to make smaller 
Java :: java foreach 
Java :: This version of the Android Support plugin for IntelliJ IDEA (or Android Studio) cannot open this project, please retry with version 4.1 or newer. 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =