{"id":27196,"date":"2018-01-03T22:16:05","date_gmt":"2018-01-03T16:46:05","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27196"},"modified":"2018-01-03T22:16:05","modified_gmt":"2018-01-03T16:46:05","slug":"java-programming-count-ways-reach-nth-stair","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-count-ways-reach-nth-stair\/","title":{"rendered":"Java Programming &#8211; Count ways to reach the n\u2019th stair"},"content":{"rendered":"<p>There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top.<\/p>\n<p><img decoding=\"async\" class=\"alignleft size-full wp-image-27197\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Staircase-Problem.png\" alt=\"Staircase Problem\" width=\"128\" height=\"140\" \/><\/p>\n<p>Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p><strong>More Examples:<\/strong><\/p>\n<pre>Input: n = 1\r\nOutput: 1\r\nThere is only one way to climb 1 stair\r\n\r\nInput: n = 2\r\nOutput: 2\r\nThere are two ways: (1, 1) and (2)\r\n\r\nInput: n = 4\r\nOutput: 5\r\n(1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2)<\/pre>\n<p>We can easily find recursive nature in above problem. The person can reach n\u2019th stair from either (n-1)\u2019th stair or from (n-2)\u2019th stair. Let the total number of ways to reach n\u2019t stair be \u2018ways(n)\u2019. The value of \u2018ways(n)\u2019 can be written as following.<\/p>\n<pre>    ways(n) = ways(n-1) + ways(n-2)\r\n<\/pre>\n<p>The above expression is actually the expression for Fibonacci numbers, but there is one thing to notice, the value of ways(n) is equal to fibonacci(n+1).<\/p>\n<p>ways(1) = fib(2) = 1<br \/>\nways(2) = fib(3) = 2<br \/>\nways(3) = fib(4) = 3<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>So we can use function for fibonacci numbers to find the value of ways(n). Following is C++ implementation of the above idea.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class stairs<br\/>{<br\/>    \/\/ A simple recursive program to find n&#039;th fibonacci number<br\/>    static int fib(int n)<br\/>    {<br\/>       if (n &lt;= 1)<br\/>          return n;<br\/>       return fib(n-1) + fib(n-2);<br\/>    }<br\/>     <br\/>    \/\/ Returns number of ways to reach s&#039;th stair<br\/>    static int countWays(int s)<br\/>    {<br\/>        return fib(s + 1);<br\/>    }<br\/> <br\/> <br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int s = 4;<br\/>          System.out.println(&quot;Number of ways = &quot;+ countWays(s));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Number of ways = 5<\/pre>\n<p>The time complexity of the above implementation is exponential (golden ratio raised to power n). It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Generalization of the above problem<\/strong><br \/>\nHow to count number of ways if the person can climb up to m stairs for a given value m? For example if m is 4, the person can climb 1 stair or 2 stairs or 3 stairs or 4 stairs at a time.<\/p>\n<p>We can write the recurrence as following.<\/p>\n<pre>   ways(n, m) = ways(n-1, m) + ways(n-2, m) + ... ways(n-m, m)<\/pre>\n<p>Following is Java\u00a0implementation of above recurrence.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class stairs<br\/>{<br\/>    \/\/ A recursive function used by countWays<br\/>    static int countWaysUtil(int n, int m)<br\/>    {<br\/>        if (n &lt;= 1)<br\/>            return n;<br\/>        int res = 0;<br\/>        for (int i = 1; i&lt;=m &amp;&amp; i&lt;=n; i++)<br\/>            res += countWaysUtil(n-i, m);<br\/>        return res;<br\/>    }<br\/>  <br\/>    \/\/ Returns number of ways to reach s&#039;th stair<br\/>    static int countWays(int s, int m)<br\/>    {<br\/>        return countWaysUtil(s+1, m);<br\/>    }<br\/> <br\/> <br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int s = 4,m = 2;<br\/>          System.out.println(&quot;Number of ways = &quot;+ countWays(s,m));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Number of ways = 5<\/pre>\n<p>The time complexity of above solution is exponential. It can be optimized to O(mn) by using dynamic programming. Following is dynamic programming based solution. We build a table res[] in bottom up manner.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class stairs<br\/>{<br\/>    \/\/ A recursive function used by countWays<br\/>    static int countWaysUtil(int n, int m)<br\/>    {<br\/>        if (n &lt;= 1)<br\/>            return n;<br\/>        int res = 0;<br\/>        for (int i = 1; i&lt;=m &amp;&amp; i&lt;=n; i++)<br\/>            res += countWaysUtil(n-i, m);<br\/>        return res;<br\/>    }<br\/>    \/\/ Returns number of ways to reach s&#039;th stair<br\/>    static int countWays(int s, int m)<br\/>    {<br\/>        return countWaysUtil(s+1, m);<br\/>    }<br\/> <br\/>    \/* Driver program to test above function *\/<br\/>    public static void main (String args[])<br\/>    {<br\/>          int s = 4,m = 2;<br\/>          System.out.println(&quot;Number of ways = &quot;+ countWays(s,m));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Number of ways = 5<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming &#8211; Count ways to reach the n\u2019th stair &#8211; Dynamic Programming There are n stairs, a person standing at the bottom wants to reach the top. <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,70145,2139],"tags":[81053,81058,72847,81057,81054,81043,81044,72987,72985,72843,72844,81048,81052],"class_list":["post-27196","post","type-post","status-publish","format-standard","hentry","category-coding","category-dynamic-programming","category-java","tag-c-code-climbing-stairs","tag-climbing-stairs-in-java","tag-concept-of-dynamic-programming","tag-count-ways-to-nth-stairorder-does-not-matter","tag-count-ways-to-reach-nth-stair","tag-count-ways-to-reach-the-nth-stair","tag-count-ways-to-reach-the-nth-stair-in-c","tag-dynamic-programming-in-java","tag-dynamic-programming-java","tag-dynamic-programming-problems","tag-dynamic-programming-software","tag-how-many-numbe","tag-how-many-ways-to-climb-10-steps"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27196","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27196"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27196\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27196"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27196"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27196"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}