Question
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
关键词:递归 短路链接
Solution
什么都不能用只能乖乖递归了。好多人说这里使用了短路求值的原理,本质上不还是递归,只是用短路来作为递归的终止条件。
递归
时间复杂度:O(N)
空间复杂度:O(1)
- Python
class Solution:
def Sum_Solution(self, n):
if n == 1:
return 1
return n + self.Sum_Solution(n-1)
- C++
class Solution {
public:
int Sum_Solution(int n) {
if(n==1) return 1;
return n + Sum_Solution(n-1);
}
};
短路求值
利用&&,当前面一个为false,就直接返回,不需要思考后面的条件(递归),由此成为递归的终点。
时间复杂度:O(N)
空间复杂度:O(1)
- Python
class Solution:
def Sum_Solution(self, n):
temp = n and self.Sum_Solution(n-1)
return n + temp
- C++
class Solution {
public:
int Sum_Solution(int n) {
int ans = n;
ans && (ans += Sum_Solution(n - 1));
return ans;
}
};