zoukankan      html  css  js  c++  java
  • 递归

     1 '''
     2 递归:一个函数,在自己函数内部调用了自己的函数,称之为递归。
     3 递归函数:一个能够调用自己本身的函数称之为递归函数。
     4 
     5 凡是循环能做的递归都能做。(死循环除外)
     6 注: 在python中,递归函数要求必须有一个条件使之退出函数体。
     7 '''
     8 # def outer():
     9 #     pass
    10 # def func1():
    11 #     outer()
    12 
    13 # def func():
    14 #     print("123")
    15 #     func()
    16 # func()
    17 x = 1
    18 for i in range(1, 6):
    19     x = x * i
    20 print(x)
    21 
    22 # 递归
    23 def jx(num):
    24     if num == 0 or num == 1:
    25         return 1
    26     else:
    27         return num * jx(num-1)
    28 print(jx(5))
    29 
    30 # num=5   5 * jx(4)
    31 # num=4       4 * jx(3)
    32 # num=3           3 * jx(2)
    33 # num=2               2 * jx(1)
    34 # num=1                    1
    35 #        5 * 4 * 3 * 2 * 1
    36 
    37 # 使用递归,输出五次内容
    38 def printHello(num):
    39     if num == 0:
    40         return 0
    41     print("hello")
    42     printHello(num-1)
    43 printHello(5)
    44 
    45 print('-------------------------')
    46 num = 5
    47 def printHello():
    48     global num
    49     if num == 0:
    50         return 0
    51     num -= 1
    52     print("hello")
    53     printHello()
    54 printHello()
    55 
    56 
    57 # 输出  5+4+3+2+1 = 15
    58 def addNum(num):
    59     if num == 0:
    60         return 0
    61     else:
    62         return num + addNum(num -1)
    63 print(addNum(5))
  • 相关阅读:
    16. 3Sum Closest
    17. Letter Combinations of a Phone Number
    20. Valid Parentheses
    77. Combinations
    80. Remove Duplicates from Sorted Array II
    82. Remove Duplicates from Sorted List II
    88. Merge Sorted Array
    257. Binary Tree Paths
    225. Implement Stack using Queues
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/BKY88888888/p/11272266.html
Copyright © 2011-2022 走看看