(题目来自牛客网)
描述:
输入int型数组,询问该数组能否分成两组,使得两组中各元素加起来的和相等,并且,所有5的倍数必须在其中一个组中,所有3的倍数在另一个组中(不包括5的倍数),不是5的倍数也不是3的倍数能放在任意一组,可以将数组分为空数组,能满足以上条件,输出true;不满足时输出false。
输入描述:
第一行是数据个数,第二行是输入的数据
输出描述:
返回true或者false
示例:
输入:
4
1 5 -5 1
输出:
true
代码:
import math
def ad(five,three,other):
if not other:
if sum(five)==sum(three):
return True
else:
return False
else:
return ad(five+other[:1],three,other[1:]) or ad(five,three+other[:1],other[1:]) #深度递归
while True:
try:
n,num=int(input()),list(map(int,input().split()))
five,three,other=[],[],[]
for i in num:
if i%5==0 and math.fabs(i)>=5:
five.append(i)
elif i%3==0 and math.fabs(i)>=3:
three.append(i)
else:
other.append(i)
if ad(five,three,other):
print('true')
else:
print('false')
except:
break