递归 Created 2020-05-17 | Updated 2022-05-22
| Post Views:
Definition Recursion
the process of repeating a function, each time applying it to the result of the previous stage.
经过树形结构,和嵌套结构后的思想:可像数学函数一样,一个个嵌套,完美解决递归
演示递归 debug 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <stdio.h> void up_and_down (int ) ;int main (void ) { up_and_down(1 ); return 0 ; } void up_and_down (int n) { printf ("Level %d: n location %p\n" , n, &n); if (n < 4 ) up_and_down(n+1 ); printf ("LEVEL %d: n location %p\n" , n, &n); }
output
1 2 3 4 5 6 7 8 Level 1: n location 000000000061FE00 Level 2: n location 000000000061FDD0 Level 3: n location 000000000061FDA0 Level 4: n location 000000000061FD70 LEVEL 4: n location 000000000061FD70 LEVEL 3: n location 000000000061FDA0 LEVEL 2: n location 000000000061FDD0 LEVEL 1: n location 000000000061FE00
递归工作栈 从上述可以看出,函数调用属于后调用先返回 的过程。那么,符合栈的性质。所以,每当调用一个函数,系统就为这个函数在栈顶中分配空间,但函数返回就出栈,释放空间。存储区里包括:所有实参,局部变量,返回值。
函数思想解决简单递归
G(10)
G(9) + 10
G(8) + 9 + 10 ….
思想可以联系树的递归遍历作图,将前后节点(函数)合并得到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <stdio.h> int GrowWordNumber (int d) { if (d == 1 ) return 1 ; else { return GrowWordNumber(d - 1 ) + d; } } int main () { int num = GrowWordNumber(10 ); printf ("%d\n" , num); return 0 ; }
递归和循环
递归和倒序输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <stdio.h> void to_binary (unsigned long n) ;int main (void ) { unsigned long number; printf ("Enter an integer (q to quit):\n" ); while (scanf ("%lu" , &number) == 1 ) { printf ("Binary equivalent: " ); to_binary(number); putchar ('\n' ); printf ("Enter an integer (q to quit):\n" ); } printf ("Done.\n" ); return 0 ; } void to_binary (unsigned long n) { int r; r = n % 2 ; if (n >= 2 ) to_binary(n / 2 ); putchar (r == 0 ? '0' : '1' ); return ; }
hanoi汉诺塔 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <stdio.h> void hanoi (int n, char one, char two, char three) { if (n == 1 ) printf ("%c -> %c\n" , one, three); else { hanoi(n-1 , one, three, two); printf ("%c --> %c\n" , one, three); hanoi(n-1 , two, one, three); printf ("\n" ); } } int main () { int n = 3 ; hanoi(n, 'A' , 'B' , 'C' ); return 0 ; }