Tower of Hanoi - a classic use of recursion

<!--- Tower of Hanoi: The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy that originated from an ancient Indian legend. 
When Brahma created the world, he made three diamond pillars, on which 64 golden discs were stacked in order from bottom to top.
Brahma ordered the Brahmin to rearrange the disc on another pillar in order of size, starting from the bottom. And it is stipulated that the disc cannot be enlarged on the small disc, and
only one disc can be moved at a time between the three columns. (-------From Baidu Encyclopedia) --->


1
<! DOCTYPE html > 2 < html > 3 < head > 4 < meta charset ="UTF-8" > 5 < title ></ title > 6 < script type ="text/javascript" > function hannoi(n,a,b,c){ 11 if (n == 1 ){ 12 //console.log( ' Move the first plate from ' + a + ' to ' + c) 13 } else { 14 hannoi(n - 1 ,a,c,b); 15 //console.log( ' Move the ' + n + ' plate from ' + a + ' to ' +c); 16 hannoi(n-1,b,a,c); 17 } 18 19 } 20 21 hannoi(64,'A','B','C'); 22 23 24 </script> 25 </head> 26 <body> 27 </body> 28 </html>

Summary of recursive learning:

1. First find the critical value, that is, the value that can be obtained without calculation.
2. Find the relationship between this time and the last time, namely f(n) and f(n-1)
3. Assuming that the current function is ready to use, call itself to calculate the last running result,
Then write the result of this operation
function sum(n){
                 // alert(n); 
                // critical condition 
                if (n == 1 ){
                     return 1 ;
                }
                
                //f(n) = f(n-1)+n
                return sum(n-1)+n;
            }
            
            
            var res = sum(100 );
            console.log(res)

The above is the operation of the sum of positive integers within 100.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686854&siteId=291194637