一个数组长度为n,均分成m份,使各的和相等,求 m 的最大值,比如{3,2,4,3,6} 可以分成{3,2,4,3,6,} m=1;{3,6}{2,4,3}m=2 {3,3}{2,4}{6} m=3


nums = [3,3,9]
n = len(nums)
numsSum = sum(nums)



def judge(total, totalList, judgeList):
	if all(judgeList):
		for k in totalList:
			if sum(k) != total:
				return False
		return True

	for i,v in enumerate(nums):
		if not judgeList[i]:
			for j in totalList:
				if sum(j) + v <= total:
					judgeList[i] = 1
					j.append(v)
					if judge(total, totalList, judgeList):
						return True
					j.pop()
					judgeList[i] = 0
	return False


for m in range(n, 0, -1):
	print 'start====',m
	if numsSum % m != 0:
		continue
	totalList = [[] for i in range(m)]
	judgeList = [0] * n
	if judge(numsSum/m, totalList, judgeList):
		print 'max value is :',m
		break



版权声明:本文为zqf_CSDN原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。