Pascal's Triangle(파스카 삼각형)

제목:


Given numRows, generate the first numRows of Pascal's triangle(양휘 삼각형).For example, given numRows = 5, Return
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

분석:

  • 비귀속 실현, 수조로 실현하는 것과 유사..
  • 귀속 실현..
  • class Solution {
    public:
        vector > generate(int numRows) {
            vector> result;
            if(numRows < 1){
                return result;
            }
            vector line;
            line.push_back(1);
            result.push_back(line);
            if(numRows == 1){
                return result;
            }
            for(int i = 2; i <= numRows; i++){
                line.clear();
                line.push_back(1);
                for(int j = 0; j < i - 2; j++){
                    line.push_back(result[i - 2][j] + result[i - 2][j + 1]);
                }
                line.push_back(1);
                result.push_back(line);
            }
            return result;
        }
    };
    class Solution {
    public:
    	vector > generate(int numRows) {
    		vector v, temp;
    		vector >vv;
    
    		if (numRows == 1)
    		{
    			v.push_back(1);
    			vv.push_back(v);
    		}
    		else if (numRows > 1)
    		{
    			vv = generate(numRows-1); // numRows-1 vv vv
    			temp = vv.back();
    			//vv.clear(); // 
    			v.push_back(1);
    			for (int i = 1; i < numRows - 1; i++)
    			{
    				v.push_back(temp[i-1]+temp[i]);
    			}
    			v.push_back(1);
    			vv.push_back(v);
    		}
    		return vv;
    	}
    };

    좋은 웹페이지 즐겨찾기