[LeetCode] 6.Array and String - Pascal's Triangle Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

 

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

INPUT:. 5 
the Output: 
[ 
     [. 1], 
    [1,1], 
   [1,2,1], 
  [1,3,3,1], 
 [1,4,6,4,1] 
] 
very basic topic University of beginning to learn C or C ++ language, will exercise a question. The main achievement is to have more understanding of the two-dimensional dynamic arrays.
Method: Define the label slides, a layer of data required for calculating the acquisition layer, to calculate the value of the current layer.
class Solution {
public:
vector<vector<int>> generate(int numRows) {
    if (numRows < 1)  return{};
    if (numRows == 1) return{ {1} };
    if (numRows == 2) return{ {1},{1,1} };
    vector<vector<int>> result(numRows);
    result[0].push_back(1);
    result[1].push_back(1);
    result[1].push_back(1);
    int counter=2;
    while (counter < numRows) {
        int tag1 = 0, tag2 = 1;
        result[counter].push_back(1);
        while (1)
        {
            result[counter].push_back(result[counter - 1][tag1] + result[counter - 1][tag2]);
            tag1++;
            tag2++;
            if (tag2 >=result[counter-1].size()) {
                result[counter].push_back(1);
                break;
            }
        }
        counter++;
    }
    return result;
  }
};

 

Guess you like

Origin www.cnblogs.com/hu-19941213/p/10941861.html