From 6770fe8b150b7feaa5e79cf62fec4d977458d63c Mon Sep 17 00:00:00 2001 From: pezy-pc Date: Wed, 3 Dec 2014 08:48:46 +0800 Subject: [PATCH] added 50. Pascal's Triangle II --- 50. Pascal's Triangle II/README.md | 21 +++++++++++++++++++++ 50. Pascal's Triangle II/main.cc | 11 +++++++++++ 50. Pascal's Triangle II/solution.h | 14 ++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 50. Pascal's Triangle II/README.md create mode 100644 50. Pascal's Triangle II/main.cc create mode 100644 50. Pascal's Triangle II/solution.h diff --git a/50. Pascal's Triangle II/README.md b/50. Pascal's Triangle II/README.md new file mode 100644 index 0000000..a7ca485 --- /dev/null +++ b/50. Pascal's Triangle II/README.md @@ -0,0 +1,21 @@ +基础题,不多说,思路和 [32. Pascal's Triangle](32. Pascal's Triangle) 完全一致。 + +----- + +重点总结一下杨辉三角的本质,我们提到杨辉三角,不要老想起那个正三角形的样子,那个样子只是让你更加形象的感受杨辉三角透露出来的数学美感,但在计算机的世界里,那东西就是格式拼凑的结果而已。 + +我们应该想起的本质,其实应该是**一根皮筋**。如下图所示: + +```cpp +|1| ------> drag + +|1|2|1| ------> drag + +|1|3|3|1| ------> drag + +|1|4|6|4|1| ------> drag +``` + +这样看起来,有没有点皮筋的感觉?你拽它,越拽越长,而中间受到的力,越来越大,使劲拽,会有一种要崩的感觉。上面图里,我最大拽到了6,再使劲,那个值会越来越大。 + +所以杨辉三角,不要被什么三角迷惑,拉拉手边的皮筋,规律就在里面。 diff --git a/50. Pascal's Triangle II/main.cc b/50. Pascal's Triangle II/main.cc new file mode 100644 index 0000000..85dc90b --- /dev/null +++ b/50. Pascal's Triangle II/main.cc @@ -0,0 +1,11 @@ +#include "solution.h" +#include + +int main() +{ + Solution s; + for (auto i : s.getRow(4)) + std::cout << i << " "; + + return 0; +} diff --git a/50. Pascal's Triangle II/solution.h b/50. Pascal's Triangle II/solution.h new file mode 100644 index 0000000..e6d7444 --- /dev/null +++ b/50. Pascal's Triangle II/solution.h @@ -0,0 +1,14 @@ +#include +using std::vector; + +class Solution { +public: + vector getRow(int rowIndex) { + vector vec(rowIndex+1, 0); + vec[0] = 1; + for (int i=0; i<=rowIndex; ++i) + for (int j=i; j>0; --j) + vec[j] += vec[j-1]; + return vec; + } +};