文章目录
【一】 Recursion(递归,盗梦空间)
【1.1】 盗梦空间(阶乘)
【1.2】 代码模板
# python 递归函数
def recursion(level, param1, param2, ...)
# recursion terminator (终止条件)
if level > MAX_LEVEL:
print_result
return
# process logic in current level
process_data(level, data, ...)
# drill down
self.recursion(level+1, p1, ...)
# reverse the current level status if needed
reverse_state(level)
【二】 Divide and Conquer(分治)
【2.1】 分解问题
【2.2】 代码模板
扫描二维码关注公众号,回复:
9662295 查看本文章
# python 分治函数
def divide_conquer(problem, param1, param2, ...)
# recursion terminator (终止条件)
if problem is None:
print_result
return
# prepare data
data = prepare_data(problem)
subproblems = split_problem(problem, data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0], p1, ...)
subresult2 = self.divide_conquer(subproblems[1], p1, ...)
subresult3 = self.divide_conquer(subproblems[2], p1, ...)
...
# process and generate the final result
result = process_result(subresult1, subresult2, subresult3, ...)
【三】 Interview(面试题)
【3.1】 LeetCode 50:Pow(X 的 N 次方)
Input: 2.00000,10
Output: 1024.00000
Input: 2.00000,-1
Output: 0.25000
- 分治( )
# python1 (分治,递归)
def myPow(self, x, n):
if not n:
return 1
if n < 0: # n 为负数的情况
return 1 / self.myPow(x, -n)
if n % 2: # 奇数
return x * self.myPow(x, n-1)
return self.myPow(x*x, n/2)
- 非递归( )
# python2 (非递归)
def myPow(self, x, n):
if n < 0: # n 为负数的情况
x = 1/x
n = -n
pow = 1
while n:
if n & 1: # 奇数的情况
pow *= x
x *= x
n = n >> 1 # 位运算, 相当于 n = n / 2
return pow
【3.2】 LeetCode 169:Majority Element(求众数)
Input: [ 1, 3, 3, 2, 3 ]
Output: 3
Input: [ 1, 1, 1, 0, 2 ]
Output: 1
- 分治( )比较麻烦,不推荐
- 字典( )推荐