문제🔽
https://school.programmers.co.kr/learn/courses/30/lessons/12945
다른사람 풀이 🔽
function solution(n) {
var result = [0 , 1];
while ( result.length !== n + 1) {
var fibonacci = (result[result.length - 2] + result[result.length - 1]) % 1234567
result.push(fibonacci);
}
return result[n];
}
내풀이🔽
1. 첫번째 시도 -> 실패 ❌ ( 추정 원인: 시간복잡도 최적화 실패 )
function solution(n) {
var answer = 0;
let count =1;
const pivo = (value1,value2)=>{
++count;
if(count==n){
answer = (value1+value2)%1234567
return;
}
pivo(value2,value1+value2);
}
pivo(0,1)
return answer;
}
2. 두번째 시도 -> 성공 ⭕
function solution(n) {
let pivoArray=[0,1]
let count = 1;
while(count<n){
++count
pivoArray[count]=(pivoArray[count-1]+pivoArray[count-2])%1234567
}
return pivoArray[n]
}
느낀점😮
재귀함수를 쓸 경우 콜스택이 터질 수 있고 연산의 복잡도가 너무 올라간다는 사실은 인지하자
콜스택이 터지는 걸 방지하기 위해서 반복문으로 연산을 하고 이왕이면 수가 커진다면 최대한 컴퓨팅 메모리에 부담이 안가는 연산방법을 생각해보자
'Javascript' 카테고리의 다른 글
프로그래머스 코딩테스트 풀이(js) > 영어 끝말잇기 (lv2) (0) | 2023.06.19 |
---|---|
프로그래머스 코딩테스트 풀이(js) > 짝지어 제거하기(lv2) (0) | 2023.06.18 |
프로그래머스 코딩테스트 풀이(js) > 다음 큰 숫자(lv2) (0) | 2023.06.16 |
프로그래머스 코딩테스트 풀이(js) > 숫자의 표현(lv2) (0) | 2023.06.15 |
프로그래머스 코딩테스트 풀이(js) > 최솟값 만들기 (lv2) (0) | 2023.06.13 |