首页 > 编程语言 > 详细

【算法】 杨辉三角

时间:2014-12-26 16:06:15      阅读:304      评论:0      收藏:0      [点我收藏+]

【算法】 杨辉三角

        /// <summary>
        /// 递归方式
     /// 思路:当前楼层是首尾为1,中间为上一楼层各相邻2元素相加之和的集合
/// </summary> /// <param name="n"></param> /// <returns></returns> public static List<int> Yh(int n) { CheckInt(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++) { 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) { CheckInt(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++) { temp.Add(list[j] + list[j + 1]); //中间加入上一楼层各相邻元素相加之和 } temp.Add(1); // 末尾加入1 list = temp; // 保存缓存数据 } return list; }

【算法】 杨辉三角

原文:http://www.cnblogs.com/fzz2727551894/p/4186745.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!