0. 题目
描述
输入int型数组,询问该数组能否分成两组,使得两组中各元素加起来的和相等,并且,所有5的倍数必须在其中一个组中,所有3的倍数在另一个组中(不包括5的倍数),不是5的倍数也不是3的倍数能放在任意一组,可以将数组分为空数组,能满足以上条件,输出true;不满足时输出false。
数据范围:每个数组大小满足 1 \le n \le 50 \1≤n≤50 ,输入的数据大小满足 |val| \le 500 \∣val∣≤500
输入描述:
第一行是数据个数,第二行是输入的数据
输出描述:
返回true或者false
示例1
输入:
4
1 5 -5 1
输出:
true
说明:
第一组:5 -5 1
第二组:1
示例2
输入:
3
3 5 8
输出:
false
说明:
由于3和5不能放在同一组,所以不存在一种分法。
1. 思路
由于题目中明确说明num%30和num%50的数要放到两个arr内,所以我们可以先将三的倍数,五的倍数,其余数分配到三个arr中num_3,num_5,other。之后求和num_3与num_5,对于other中的的每个数组,均存在两种可能,分配到num_3和num_5中,我们可以利用递归的方式枚举所有可能。
PS:注意列表的性质
eg:a=[1,2,3,4,5] b=[6,7,8,9] 则b[:1]=[6],b[0]=6(注意两者并不相同),a+b[:1]=[1,2,3,4,5,6]
2. 代码
def dfs(three, five, other):
if not other:
if sum(three) == sum(five):
return True
else:
return False
#对于other中的某个数,存在两种可能,在num_3或num_5中,这两种情况中只要有一种满足要求即可
return dfs(three+other[:1], five, other[1:]) or dfs(three, five+other[:1], other[1:])
while True:
try:
n, nums = int(input()), list(map(int, input().split()))
three, five, other = [], [], []
for num in nums:
if num % 3 == 0:
three.append(num)
elif num % 5 == 0:
five.append(num)
else:
other.append(num)
if dfs(three, five, other):
print ('true')
else:
print ('false')
except:
break