코딩테스트 준비/leetcode

118. Pascal's Triangle

MAKGA 2021. 8. 8. 22:50
320x100

https://leetcode.com/problems/pascals-triangle/

 

Pascal's Triangle - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

정수가 주어졌을 때 그에 해당하는 파스칼 삼각형을 만들어야 하는 문제다.

내려갈수록 이전 줄에서 원소의 덧셈을 아랫줄의 원소로 만드는 내용인데 대략 아래와 같은 구조이다.

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

2는 윗 줄 2개의 1+1로, 3은 윗 줄 1+2, 2+1로, 4는 윗 줄 1+3, 3+1, 6은 윗 줄 3+3의 결과로 나오는 식이다.

 

<C++>

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ret(numRows);
        
        for (int i = 0; i < numRows; ++i)
        {
            ret[i].resize(i + 1);
            ret[i][0] = ret[i][i] = 1;
            
            for (int j = 1; j < i; ++j) {
                ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1];
            }
        }
        
        return ret;
    }
};

 

<Python3>

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0: return ret
        
        ret = [[1]]
        if numRows == 1: return ret

        for i in range(1, numRows):            
            row = [1]
            for j in range(1, i):
                row.append(ret[i - 1][j - 1] + ret[i - 1][j])
            row.append(1)
            ret.append(row)            
        return ret

 

320x100

'코딩테스트 준비 > leetcode' 카테고리의 다른 글

88. Merge Sorted Array  (0) 2021.08.10
14. Longest Common Prefix  (0) 2021.08.09
1. Two Sum  (0) 2021.08.07
50. Pow(x, n)  (0) 2021.08.07
49. Group Anagrams  (0) 2021.08.07