知识点

递归

思路

求官方出一个标准答案,我看看怎么不用循环和条件判断写阶乘。对于此题,不用循环可以用递归方式写,不过注意判断递归的终止条件以及数据范围即可

代码c++

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
     long long int ans=1;
     void dfs(int n)
     {  if(n==1)return;
        ans=ans*n%1000000007;
        dfs(n-1);
     }
    int factorial(int n) {
        // write code here
        dfs(n);
        return ans;
    }
};