LeetCode: Pascal's Triangle II

本文提供了一种高效的方法来计算帕斯卡三角形的特定行。使用C++和C#两种语言实现了算法,通过迭代填充每行元素来构建整个行。此方法适用于动态规划问题,并为理解组合数学中的基本概念提供了帮助。

小失误,基本一次过

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<int> pre;
 7         for (int i = 0; i <= rowIndex; i++) {
 8             vector<int> cur;
 9             if (!pre.size()) {
10                 cur.push_back(1);
11                 pre = cur;
12             }
13             else {
14                 for (int j = 0; j <= pre.size(); j++) {
15                     if (!j || j == i) cur.push_back(1);
16                     else cur.push_back(pre[j-1]+pre[j]);
17                 }
18                 pre = cur;
19             }
20         }
21         return pre;
22     }
23 };

 C#

 1 public class Solution {
 2     public List<int> GetRow(int rowIndex) {
 3         List<int> ans = new List<int>();
 4         for (int i = 0; i <= rowIndex; i++) {
 5             List<int> cur = new List<int>();
 6             if (ans.Count == 0) {
 7                 cur.Add(1);
 8                 ans = new List<int>(cur.ToArray());
 9             }
10             else {
11                 for (int j = 0; j <= ans.Count; j++) {
12                     if ( j == 0 || j == i) cur.Add(1);
13                     else cur.Add(ans[j-1] + ans[j]);
14                 }
15                 ans = new List<int>(cur.ToArray());
16             }
17         }
18         return ans;
19     }
20 }
View Code

 

转载于:https://www.cnblogs.com/yingzhongwen/archive/2013/04/19/3029874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值