题目描述:
给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N?
首先,刚开始读错题目了,以为是子集和就行,后来发现是连续子集;想到用子集树,但是超时了
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
self.res = 0
nums = list(range(1,(N+1)//2+1))
self.backtrack(nums,N,0,0,[])
if N<=2:
return 1
return self.res+1
def backtrack(self,nums,tar,index,pre,path):
if tar==0:
self.res += 1
return
for i in range(index,len(nums)):
if nums[i]<=tar and (len(path)==0 or nums[i] == path[-1]+1):
self.backtrack(nums,tar-nums[i],i+1,i,path+[nums[i]])
参考答案:其实不难,开动脑筋想一想,就是一个等差数列问题,把公式写出来,就很好判断
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
if N<=2:
return 1
res = 0
for i in range(1,N+1):
m = N-i*(i-1)/2
if m <= 0 :
break
if m%i==0:
res += 1
return res