Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to efficiently generate all combinations of well-formed parentheses for n pairs of them, in Java?

/*
	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 :: how to extract decimal vqalue from float in android studio 
Java :: java swing enter key press event 
Java :: use view binding in fragment 
Java :: keytool error: java.io.IOException: keystore password was incorrect java.io.IOException: keystore password was incorrect flutter 
Java :: Lunar New Year 
Java :: linked list sorting in java 
Java :: gradle require java version 
Java :: java int length 
Java :: char variable java 
Java :: java loop object 
Java :: javafx every second 
Java :: is prime java 
Java :: find duplicate value in array using java 
Java :: selet all elemnts 
Java :: java convert list to page 
Java :: Java Copying Arrays Using copyOfRange() method 
Java :: how to split a string in java 
Java :: java get number of days in month 
Java :: localdate add months in java 
Java :: bufferedreader java 
Java :: hanoi tower java 
Java :: android studio textbox change text 
Java :: specify decimal places java 
Java :: prime number between given range in java 
Java :: java or symbol 
Java :: caesar cipher java 
Java :: float vs double java 
Java :: Error: Could not find or load main class -Djava.library.path=.home.hdoop.hadoop-3.3.0.lib.native 
Java :: android studio Clearing shared preferences; 
Java :: remove spaces at beginning and end of string java 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =