【算法】 杨辉三角

【算法】 杨辉三角

        /// <summary>
        /// 递归方式  : 思路简单但效率比循环方式低,递归次数越多,性能越低
        /// 思路:当前楼层是首尾为1,中间为上一楼层各相邻2元素相加之和的集合
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static List<int> Yh(int n)
        {
            var list = new List<int> { 1 }; // 第一楼层
            if (n <= 1)
            {
                return list;
            }
            var lastList = Yh(n - 1); // 用递归的方式获取上一楼层的集合
            for (int i = 0; i < lastList.Count - 1; i++)
            {
                checked // 检查算术溢出
                {
                    list.Add(lastList[i] + lastList[i + 1]); //中间加入上一楼层各相邻元素相加之和
                }
            }
            list.Add(1); // 末尾加入1
            return list;
        }

        /// <summary>
        /// 循环方式
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static List<int> YhFor(int n)
        {
            var list = new List<int> { 1 }; // 第一楼层
            for (int i = 1; i < n; i++) // 遍历楼层数
            {
                var temp = new List<int> { 1 }; // 当前楼层的缓存
                for (int j = 0; j < list.Count - 1; j++)
                {
                    checked
                    {
                        temp.Add(list[j] + list[j + 1]); //中间加入上一楼层各相邻元素相加之和
                    }
                }
                temp.Add(1); // 末尾加入1
                list = temp; // 保存缓存数据
            }
            return list;
        }
原文地址:https://www.cnblogs.com/fzz2727551894/p/4186745.html