记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
2、数据结构:
递归
3、题解:
方法1:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.res = 0
def Sum_Solution(self, n):
# write code here
n > 1 and self.Sum_Solution(n - 1)
self.res += n
return self.res
下面提供两种方法,但是用了此题的限制,只作为开阔一下思路用,不作为满足此题的题解。
方法2:平均计算
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return n * (n + 1) // 2
方法3:迭代
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
res = 0
for i in range(1,n + 1):
res += i
return res
4、复杂度分析:
方法1:
时间复杂度都为O(N)
空间复杂度都为O(N)