1、递归
2、迭代
3、逻辑
递归法
class Solution:
def sumNums(self, n: int) -> int:
if n < 1:
return 0
return n + self.sumNums(n - 1)
s = Solution()
print(s.sumNums(5))
def sumNums(n):
if n == 1: return 1
n += sumNums(n - 1)
return n
print(sumNums(5))
class Solution:
def __init__(self):
self.res = 0
def sumNums(self, n: int) -> int:
n > 1 and self.sumNums(n - 1)
self.res += n
return self.res
s = Solution()
print(s.sumNums(5))