From 2c3b290768447ac9c2e5e48afbbebb0fe1d3879a Mon Sep 17 00:00:00 2001 From: yottalogical Date: Fri, 22 Feb 2019 13:03:22 -0500 Subject: [PATCH] Simplify waysToClimb() This is a more orthodox way of solving a problem recursively. The exit condition is much cleaner. --- chapter-12/waysToClimb.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/chapter-12/waysToClimb.java b/chapter-12/waysToClimb.java index 9d78465..393ea66 100644 --- a/chapter-12/waysToClimb.java +++ b/chapter-12/waysToClimb.java @@ -8,16 +8,17 @@ */ public static void waysToClimb(int n) { - waysToClimb(n, 0, "["); + if (n > 0) { + waysToClimb(n, 0, "["); + } } private static void waysToClimb(int n, int position, String result) { - if (n == position) { - int index = result.lastIndexOf(","); - if (index != -1) { - result = result.substring(0, index) + "]"; - System.out.println(result); - } + if (n - 1 == position) { + System.out.println(result + "1]"); + } else if (n - 2 == position) { + waysToClimb(n, position + 1, result + "1, "); + System.out.println(result + "2]"); } else if (n > position) { waysToClimb(n, position + 1, result + "1, "); waysToClimb(n, position + 2, result + "2, ");