Leetcode Question 118---Yang Hui's Triangle

Leetcode link: link .
Insert picture description here
Problem-solving ideas: ①Understanding the meaning of
the return value in the problemvector<vector<int>>
Insert picture description here

②Make a basic outline of Yang Hui's triangle shape. Reserve several rows of space
for vector<int>the array I created , and observe that the end of each array is 1, and the other places are only 0.
Insert picture description here

③Find those places that are all 0, because the title says "In Yang Hui's triangle, each number is the sum of its upper left and upper right numbers ", so it is analogous to wanting to traverse a two-dimensional array. Fill in the value. Eventually return this typevector<vector<int>>

class Solution {
    
    
public:
    vector<vector<int>> generate(int numRows) {
    
    
        //vector<vector<int>> 需要好好的理解一下这个返回值,vector里面还嵌套了有个vector
        vector<vector<int>> vv;
        vv.resize(numRows,vector<int>());
        //这样杨辉三角的初始位置就已经出现了
        for(size_t i = 0;i < vv.size();++i)
        {
    
    
            vv[i].resize(i+1,0);
            //然后后面就想象成一个二维数组去思考
            vv[i][0] = 1;
            vv[i][vv[i].size()-1] = 1;
        }
        //此时就是要把为0的位置都填上(左上角的值和右上角的值相加的结果)   
        for(size_t i = 0;i < vv.size();++i)
        {
    
    
            for(size_t j = 0; j<vv[i].size();++j)
            {
    
    
                if(vv[i][j] == 0)
                {
    
    
                    vv[i][j] = vv[i-1][j-1] + vv[i-1][j];
                }
            }
        }     
        return vv;
    }
};

Guess you like

Origin blog.csdn.net/MEANSWER/article/details/115351756