Coding Test/SW Expert Academy
[SWEA] 2005. 파스칼의 삼각형 c++
owls
2022. 11. 15. 10:30
728x90
- 문제
크기가 N인 파스칼의 삼각형을 만들어야 한다.
- 입력
1 4 |
- 출력
#1 1 1 1 1 2 1 1 3 3 1 |
- 문제 해결
이전 행렬의 j, j+1 열의 값을 더하면 현재의 값이 된다.
index범위가 벗어난다면 0으로 계산하면 된다.
#include<iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
int test_case;
int T;
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
int n = 0;
cin >> n;
cout << "#" <<test_case<<endl;
vector<vector<int> > vec(n, vector<int>(n, 0));
vec[0][0] = 1;
cout << 1 << endl;
for(int i = 1; i < n; i++){
for(int j = 0; j < n; j++){
int y1 = 0, y2 = 0;
if( j - 1 >= 0 ){
y1 = vec[i-1][j-1];
}
else{
y1 = 0;
}
if( j + 1 <= n){
y2 = vec[i-1][j];
}
else{
y2 = 0;
}
vec[i][j] = y1 + y2;
if( vec[i][j] != 0){
cout << vec[i][j] << " ";
}
}
cout << endl;
}
}
return 0;
}
728x90