题解 | #杨辉三角(二)# 使用排列组合公式

杨辉三角(二)

https://www.nowcoder.com/practice/486a9408fe2d4912843795c25d43acc2

C_n^m=\frac{n\cdot (n-1)\cdot (n-2) \cdot\cdot\cdot (n-m+1)}{1\cdot\ 2\cdot 3 \cdot \cdot \cdot m} \\
C_n^m=C_n^{n-m}

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param num int整型
     * @return int整型一维数组
     */
    public int[] getRow (int num) {
        // write code here
        int[] res = new int[num + 1];
        res[0] = 1;
        res[num] = 1;
        int top = num; // 分子,从num开始减小,
        int bottom = 1; // 分母,从1开始增加
        for (int i = 1; i <= num / 2; i++) { // 只遍历一半
            int cur = (int) ((long)res[i - 1] * top / bottom); // 使用long防止溢出
            res[i] = cur;
            res[num - i] = cur;
            top--;
            bottom++;
        }
        return res;
    }
   
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:25
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务