Vison's Blog
所有文章
文章总览
编辑器
Publications
About Me
Search
目录
#toc-container
下载Markdown文件
【4.1】LeetCode每日一题· 笨阶乘
2021年04月01日 11时30分
标签:
LeetCode
dfs
数学
## 题目描述 通常,正整数`n`的阶乘是所有小于或等于`n`的正整数的乘积。例如,`factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`。 相反,我们设计了一个笨阶乘`clumsy`:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:`乘法(*)`,`除法(/)`,`加法(+)`和`减法(-)`。 例如,`clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`。然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。 另外,我们使用的除法是地板除法(floor division),所以`10 * 9 / 8`等于`11`。这保证结果是一个整数。 实现上面定义的笨函数:给定一个整数N,它返回 N 的笨阶乘。 #### 示例1 ``` 输入:4 输出:7 解释:7 = 4 * 3 / 2 + 1 ``` #### 示例2 ``` 输入:10 输出:12 解释:12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1 ``` #### 提示 ``` 1 <= N <= 10000 -2^31 <= answer <= 2^31 - 1 (答案保证符合 32 位整数。) ``` #### 来源 > 来源:力扣(LeetCode) > 链接:[题目链接](https://leetcode-cn.com/problems/clumsy-factorial/ "题目链接") ## 解题思路 记$$i$$的笨阶乘为$$C(i)$$。通过列举笨阶乘的前面几项,可以发现如下的规律: ```katex \displaystyle C(1) = 1 ``` ```katex \displaystyle C(2) = 2 \times 1 ``` ```katex \displaystyle C(3) = 3 \times 2 \bigg/ 1 ``` ```katex \displaystyle C(4) = 4\times3 \bigg/ 2+1 ``` ```katex \displaystyle C(5) = 5\times4 \bigg/ 3+2-1 ``` ```katex \displaystyle C(6) = 6\times5 \bigg/ 4+3-2\times1 ``` ```katex \displaystyle C(7) = 7\times6 \bigg/ 5+4-3\times2 \bigg/ 1 = 7\times6 \bigg/ 5+4+C(4)- 2*\left[ 3\times2 \bigg/ 1\right] ``` ```katex \displaystyle C(8) = 8\times7 \bigg/ 6+5-4\times3 \bigg/ 2+1 = 8\times7 \bigg/ 6+5 +C(5) - 2\times\left[ 4\times3 \bigg/ 2 \right] ``` 观察式子,可以得出当 $$n \leq 7$$时,有 ```katex \displaystyle C(n) = \lfloor \frac{n(n-1)}{n-2} \rfloor + (n-3) - 2 \lfloor \frac{(n-4)(n-5)}{n-6}\rfloor + C(n-4), ``` 而当$$n < 7$$时,直接手算出答案即可。因此,可以使用递归计算出笨阶乘的值。 时间复杂度:$$O(n)$$ 空间复杂度:$$O(n)$$,为递归深度 Tips: 也可以使用[数学方法](https://leetcode-cn.com/problems/clumsy-factorial/solution/ben-jie-cheng-by-leetcode-solution-deh2/)在$$O(1)$$时间和空间求解。 ### 代码 ```cpp class Solution { public: int clumsy(int N) { switch(N){ case 1:{ return 1; } case 2:{ return 2; } case 3:{ return 6; } case 4:{ return 7; } case 5:{ return 7; } case 6:{ return 8; } default:{ return clumsy(N-4) + (N-3) + N*(N-1)/(N-2) - 2*((N-4)*(N-5)/(N-6)); } } } }; ``` ## 用时和内存 > 执行用时:0 ms,在所有 C++提交中击败了100.00%的用户 > 内存消耗:5.9 MB,在所有 C++提交中击败了44.85%的用户
所有评论
暂无评论
新增评论
评论
邮箱
邮箱仅作验证使用
图形验证码
邮箱验证码
发送验证码
发表评论
所有评论
暂无评论