暴力遞歸之求階乘、漢諾塔問題、字符串所有子序列、字符串的所有子串 python實現


暴力遞歸:

  • 把問題轉化為規模縮小了的同類問題的子問題
  • 有明確的不需要繼續進行遞歸的條件(base case)
  • 有當得到了子問題的結果之后的決策過程
  • 不記錄每一個問題的解

1.給定任意正整數n,求n的階乘

1 def getFactorial(n):
2     if n == 1:
3         return 1
4     return n*getFactorial(n-1)

2.打印n層漢諾塔從最左邊移動到最右邊的全部過程

1 # 漢諾塔問題
2 # O(2**n)
3 def hanoi(n, A, B, C):
4     if n == 1:
5         print('move %s to %s' % (A, C))
6     else:
7         hanoi(n-1, A, C, B)
8         hanoi(1, A, B, C)
9         hanoi(n-1, B, A, C)

3.打印一個字符串的全部子序列,包括空字符串

1 # 求字串的所有子序列
2 def printAllSubsquence(test, i, res):
3     if i == len(test):
4         print(res)
5         return
6     printAllSubsquence(test, i+1, res)              # 當前位置字符不加入
7     printAllSubsquence(test, i+1, res + test[i])    # 當前位置字符加入  

4.打印一個字符串的全部排列,要求不要出現重復的排列

1 # 求字串的全排列  輸入為list
2 def printAllPermutations(test, i):
3     if i == len(test):
4         print(''.join(test))
5         return
6     for j in range(i, len(test)):
7         test[i], test[j] = test[j], test[i]         # 依次與當前及之后的數交換
8         printAllPermutations(test, i+1)             # 打印當前數之后的全排列
9         test[i], test[j] = test[j], test[i]         # 把交換了的數字交換回去


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM