YJ의 새벽
피보나치수열 본문
- 피보나치수열
-- 다음 항이 이전 두개의 합으로 표현되는 수열.
--재귀함수로 피보나치수열을 구현
--반복문을 이용한 구현
--동적계획법을 이용한 구현.
public class Fibonacci {
public Fibonacci() { // 20 번째 값을 구한다.
int result = recursion(20);
System.out.println(result);
repeat(20);
dp(20);
}
private int recursion(int n) { // 재귀함수로 구현.
if( n <= 2 ) {
return 1;
}else {
return recursion (n-1) + recursion (n-2);
}
}
private void repeat(int n) { // 반복문으로 구현.
int a = 1, b = 1, c = 1;
for(int i = 3; i <=n ; i++) {
c = a+b;
a = b;
b = c;
}
System.out.println(c);
}
private void dp(int n) { // 배열로 구현 .
int[] dpArray = new int [n+1];
dpArray[1] = 1;
dpArray[2] = 1;
for(int i = 3 ; i<= n ; i++) {
dpArray[i]=dpArray[i-1]+dpArray[i-2];
}
System.out.println(dpArray[n]);
}
public static void main(String[] args) {
new Fibonacci();
}
}
어라운드 허브 스튜디오 - Around Hub Studio
우리에게 필요한 정보를 담는 '어라운드 허브 스튜디오'입니다! 📌 영상은 매주 수요일 7시 업로드 중입니다. [ 정보 ] 알고 싶은 컨텐츠, 동영상 건의 👉 around.hub.official@gmail.com 도서 판매 👉 서
www.youtube.com
'SelfStudy > JAVA 로 배우는 알고리즘' 카테고리의 다른 글
이진트리 (0) | 2023.02.20 |
---|---|
DFS,BFS (0) | 2023.02.20 |
자료구조 ? (0) | 2023.02.20 |
Comments