MCPcopy Create free account
hub / github.com/careercup/ctci / addParen

Method addParen

java/Chapter 9/Question9_6/QuestionB.java:7–23  ·  view source on GitHub ↗
(ArrayList<String> list, int leftRem, int rightRem, char[] str, int count)

Source from the content-addressed store, hash-verified

5public class QuestionB {
6
7 public static void addParen(ArrayList<String> list, int leftRem, int rightRem, char[] str, int count) {
8 if (leftRem < 0 || rightRem < leftRem) return; // invalid state
9
10 if (leftRem == 0 && rightRem == 0) { /* all out of left and right parentheses */
11 String s = String.copyValueOf(str);
12 list.add(s);
13 } else {
14 if (leftRem > 0) { // try a left paren, if there are some available
15 str[count] = '(';
16 addParen(list, leftRem - 1, rightRem, str, count + 1);
17 }
18 if (rightRem > leftRem) { // try a right paren, if there�s a matching left
19 str[count] = ')';
20 addParen(list, leftRem, rightRem - 1, str, count + 1);
21 }
22 }
23 }
24
25 public static ArrayList<String> generateParens(int count) {
26 char[] str = new char[count*2];

Callers 1

generateParensMethod · 0.95

Calls 1

addMethod · 0.45

Tested by

no test coverage detected