Python是一種非常流行的編程語言,尤其在算法設計方面有著廣泛應用。以下是一些常見的Python算法設計技巧:
#1. 遞歸
def fibonacci(n):
if n<= 1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(5)) #輸出5
#2. 動態規劃
def maxSubArray(nums):
if not nums:
return 0
curSum = maxSum = nums[0]
for i in range(1, len(nums)):
curSum = max(nums[i], curSum + nums[i])
maxSum = max(maxSum, curSum)
return maxSum
print(maxSubarray([-2,1,-3,4,-1,2,1,-5,4])) #輸出6(對應子數組[4,-1,2,1])
#3. 貪心算法
def canJump(nums):
maxPos = 0
for i, num in enumerate(nums):
if i<= maxPos:
maxPos = max(maxPos, i + num)
if maxPos >= len(nums) - 1:
return True
return False
print(canJump([2,3,1,1,4])) #輸出True
#4. 分治算法
def mergeSort(arr):
if len(arr)<= 1:
return arr
mid = len(arr) // 2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])
return merge(left, right)
def merge(left, right):
sortedArr = []
i = j = 0
while i< len(left) and j< len(right):
if left[i]< right[j]:
sortedArr.append(left[i])
i += 1
else:
sortedArr.append(right[j])
j += 1
sortedArr += left[i:]
sortedArr += right[j:]
return sortedArr
print(mergeSort([3,2,1,4,7,6,5])) #輸出[1, 2, 3, 4, 5, 6, 7]