118. Pascal's Triangle

2022. 3. 28. 23:13PS/LeetCode

[문제 접근법]

- 양쪽 대각선은 다 1이고, 그 외 나머지 값은 윗 줄에서 하나씩 더해서 내려온다는 것을 알 수 있다.

따라서, 점화식을 세워서 증명하고 그 증명한 점화식이 맞으면 구현을 한다.

 점화식 : F[i][j] = F [i-1][j] + F [i-1][j-1] (단, i=0 || i == J일 때 제외)

 

그림 1- 파스칼 삼각형 설명




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]

 - F [i][j] = F [i-1][j] + F [i-1][j-1] (단, i=0 || i == J일 때 제외)라는 점화식을 통해 문제를 해결하였다.

 

class Solution {
    public List<List<Integer>> generate(int numRows) {
   List<List<Integer>> list = new ArrayList<>();
        List<Integer> cur = null,prev=null;
        
        for (int i = 0; i < numRows; ++i) {
            cur = new ArrayList<>();

            for (int j = 0; j <= i; ++j) {
                if (j == 0 || i == j)
                    cur.add(1);

                else
                    cur.add(prev.get(j) + prev.get(j - 1));
            }

            prev=cur;
            list.add(cur);
            
        }

        return list;
    }
}
반응형

'PS > LeetCode' 카테고리의 다른 글

509. Fibonacci Number  (0) 2022.03.27
338. Counting Bits  (0) 2022.03.27