http://oj.leetcode.com/problems/pascals-triangle/ 杨辉三角
先分析数据,找出规律
ans[row][col] = ans[row-1][col-1]+ans[row-1][col]
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: vector<vector<int> > generate(int numRows) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<vector<int> > ans; ans.clear(); if(numRows<=0) return ans; //1 vector<int> onepiece; onepiece.push_back(1); ans.push_back(onepiece); if(numRows == 1) return ans; //2 onepiece.clear(); onepiece.push_back(1); onepiece.push_back(1); ans.push_back(onepiece); if(numRows == 2) return ans; //3... for(int row = 2;row < numRows;row++) { onepiece.clear(); for(int col = 0;col <= row;col++) { if(col ==0 || row == col) onepiece.push_back(1); else onepiece.push_back(ans[row-1][col-1]+ans[row-1][col]); } ans.push_back(onepiece); } return ans; } }; int main() { Solution mysolution; mysolution.generate(1); return 0; }