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 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
문제 풀이
난이도 easy
dp로 구현하면 되는 문제이다. 자바로 구현방법 익히기!!!
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> tr = new ArrayList<List<Integer>>();
if(numRows == 0){
return tr;
}
tr.add(new ArrayList<>());
tr.get(0).add(1);
for(int i=1; i<numRows; i++){
List<Integer> row = new ArrayList<>();
List<Integer> prev = tr.get(i-1);
row.add(1);
for(int j=1; j<i; j++){
row.add(prev.get(j-1) + prev.get(j));
}
row.add(1);
tr.add(row);
}
return tr;
}
}
아래는 c이다.
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> result;
if(numRows == 0){
return result;
}
result.push_back({1});
if(numRows == 1){
return result;
}
result.push_back({1,1});
if(numRows == 2){
return result;
}
for(int i = 3; i<=numRows; i++){
vector<int> cur(i,0);
result.push_back(cur);
result[i-1][0] = result[i-1][i-1] = 1;
for(int j=1; j<i-1; j++){
result[i-1][j] = result[i-2][j] + result[i-2][j-1];
}
}
return result;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 122] Best Time to Buy and Sell Stock II (0) | 2020.11.20 |
---|---|
[leetcode 125] Valid Palindrome (0) | 2020.11.20 |
[leetcode 66] Plus One (0) | 2020.11.19 |
[leetcode 88] Merge Sorted Array (0) | 2020.11.19 |
[leetcode 69] Sqrt(x) (0) | 2020.11.18 |
댓글