Pascal's Triangle
문제 설명
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
제한 사항
- 1 <= numRows <= 30
입출력 예
Example 1:
Input : numRows = 5
Output : [[1], [1.1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
Example 2:
Input : numRows = 1
Output : [[1]]
Python 코드
Python 8ms code
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSameTree(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
* 참고 링크 :
C++ 코드
C ++ 100% 0ms code
- String으로 바꾸지 않고 맨 뒤의 값과 맨 앞의 값을 비교하면서 푼 코드
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) // if the two nodes are empty nodes, return true
return true;
else if((p == NULL && q != NULL) || (p != NULL && q == NULL)) // if only one of the nodes from p and q is emtpy, 2 trees are not equal
return false;
else
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
// First we compare the values in each node from p and q. Then, use a recursive method, call isSameTree function with left nodes of p and q as parameters. Do the same for the right nodes.
}
};
* 참고 링크 :
출처
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 234. Palindrome Linked List (0) | 2022.01.14 |
---|---|
[Leet Code] 136. Single Number (0) | 2022.01.13 |
[Leet Code] 15. 3Sum 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 2. Add Two Numbers 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 100. Same Tree (0) | 2022.01.05 |