From 2c5e74be8746715771c329ca6c51fe03a1d40473 Mon Sep 17 00:00:00 2001 From: Bogdan Popov Date: Tue, 11 Oct 2016 05:01:40 +0300 Subject: [PATCH 1/2] chapter Recursion, task 3 added --- src/TechInterview/Parenthesis.java | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/TechInterview/Parenthesis.java diff --git a/src/TechInterview/Parenthesis.java b/src/TechInterview/Parenthesis.java new file mode 100644 index 0000000..86d6897 --- /dev/null +++ b/src/TechInterview/Parenthesis.java @@ -0,0 +1,40 @@ +package TechInterview; + +public class Parenthesis { + + +// Implement an algorithm to print all valid (e.g., properly opened and closed) combinations +// of n-pairs of parentheses. + + public static void parenthesis(int open, int closed, String answer) { + + if (open == 0 && closed == 0) { + System.out.printf("%s\n", answer); + } + if (open > 0) { + parenthesis(open - 1, closed + 1, answer + "("); + } + if (closed > 0) { + parenthesis(open, closed - 1, answer + ")"); + } + + } + + + public static void solution(int n) { + + parenthesis(n, 0, ""); + + } + + public static void main(String[] args) { + + solution(3); + + } + +} + + + + From 76b657e15df47ef5b9d06bb3f4c93b35ac450c3f Mon Sep 17 00:00:00 2001 From: Bogdan Date: Wed, 12 Oct 2016 11:43:02 +0300 Subject: [PATCH 2/2] some spaces removed --- src/TechInterview/Parenthesis.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/TechInterview/Parenthesis.java b/src/TechInterview/Parenthesis.java index 86d6897..35b6b4d 100644 --- a/src/TechInterview/Parenthesis.java +++ b/src/TechInterview/Parenthesis.java @@ -1,8 +1,7 @@ package TechInterview; public class Parenthesis { - - + // Implement an algorithm to print all valid (e.g., properly opened and closed) combinations // of n-pairs of parentheses. @@ -20,7 +19,6 @@ public static void parenthesis(int open, int closed, String answer) { } - public static void solution(int n) { parenthesis(n, 0, ""); @@ -32,9 +30,4 @@ public static void main(String[] args) { solution(3); } - } - - - -