本文仅供个人学习使用,免费分享。每日更新,建议关注收藏!
目前[机试指南]本系列已经达到字数10w+,所以按原每个章节拆开发布,点击目录跳转。
本站友情链接:
- c/c++算法题指南
严书代码
c/c++大复习1
c/c++大复习2 - python算法题指南
牛客华为机试103精华
python输入输出大全
python语法
PAT甲级真题刷题笔记 共179道 - python官方文档
python官方文档 - 机试指南系列
基础篇
贪心篇
递归分治搜索篇
数据结构进阶篇(树/图/优先队列)
数学问题篇
动态规划篇
STL篇
递归与分治
递归需要具备的条件:子问题与原问题相同只是规模更小+有出口
例题8.2 汉诺塔
www.lintcode.com/problem/169/
class Solution:
"""
@param n: the number of disks
@return: the order of moves
"""
result=[]
def move(self,_from,_to):
self.result.append("from {} to {}".format(_from,_to))
#print(self.result)
def hanoi(self,n,_from,_to):
for item in ['A','B','C']:
if(item !=_from and item!=_to):
other=item
if(n==1):
self.move(_from,_to)
return
else:
self.hanoi(n-1,_from,other)
self.move(_from,_to)
self.hanoi(n-1,other,_to)
return
def tower_of_hanoi(self, n: int) -> List[str]:
# write your code here
self.result=[]
self.hanoi(int(n),'A','C')
return self.result
习题8.1 杨辉三角形(西北工业大学复试上机题) http://t.cn/Ai0KcLRI 链接失效
习题8.2 全排列(北京大学复试上机题) http://t.cn/Ai0K0hXZ
#最简单的方法
import sys
import itertools
for line in sys.stdin:
a = list(line)
a=a[:-1]
for item in itertools.permutations(a,len(a)):
print(''.join(item))
#老老实实方法
import sys
result=[]
def permutation(l,num,s):
global result
#print('l,num,s',l,num,s)
for i in range(len(l)):
if(num==0):
if(s not in result):
result.append(s)
# print(result)
return
if(l[i] not in s):
s+=l[i]
permutation(l,num-1,s)
s=s[:-1]
else: continue
return result
for line in sys.stdin:
a = list(line)
a=a[:-1]
#print(a)
s=''
result=permutation(a,len(a),s)
for item in result:
print(''.join(item))
分治:分而治之,把原问题分解成多个小的彼此互相独立且与原问题相同或相似的子问题,直到最后的子问题直接能够求解。所以会使用递归。步骤3步,分、治、合。
由此可区分开,快排是递归,归并排序是分治。
习题8.3 2的幂次方(上海交通大学复试上机题) http://suo.im/5D5hnX
做这种题的秘诀就是先举个小的例子写递归,然后进行嵌套即可
import sys
dp=['0','2(0)','2','2+2(0)','2(2)'] #1,2,3,4
num=['']*14
def divide(x,s,flag):
#if(flag==1):print('into subprogram')
bi_a=bin(x)
bi_a=str(bi_a)[2:]
j=len(bi_a)
#print('bi_x',bi_a)
for i in range(len(bi_a)):
j-=1
if(bi_a[i]=='1'):
#print(j)
if(j>2):
s+='2('
flag=1
s=divide(j,s,flag)
s+=')'
flag=0
#print('out subprogram',s)
elif (j==0):
s+='2(0)'
elif (j==1):
s+='2'
elif(j==2):
s+='2(2)'
s+='+'
s=s.rstrip('+')
if(flag==0):
dp.append(s)
#print('every end ',s)
return s
for line in sys.stdin:
a = int(line)
flag=0 # 1时还在子程序里
s=''
'''
for i in range(5,15):
print('jiexi',i)
divide(i,s,flag)
print(dp[8:])
'''
divide(a,s,flag)
print(dp[-1])
#print(dp)
https://www.lintcode.com/problem/371/
class Solution:
"""
@param n: An integer
@return: An array storing 1 to the largest number with n digits.
"""
def numbersByRecursion(self, n):
# write your code here
if n==0:
return []
if