728x90
🎯 재귀함수 : 자기 자신을 부르는 함수
🏃🏻 귀납적으로 문제를 해결하는 방법
* 순차적 계산법
A를 계산한다. A를 이용해서 B를 계산한다. B를 이용해서 C를 계산한다....
* 귀납적 계산법
"나"를 계산하기 위해 또 다시 "나"를 활용한다.
🏃🏻 재귀함수 디자인을 위한 3가지 절차
1) 함수의 역할을 정확하게 정의한다.
2) 기저조건(Base Condition)에서 함수가 제대로 동작함을 보인다.
3) 함수가 (작은 input에 대해) 제대로 동작한다고 가정하고 함수를 완성한다.
🎯 문제
✍️ 팩토리얼 구하기
- 5!을 출력하시오.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class RecursiveCall {
public static int getFactorial(int n) {
if (n <= 1) {
return 1;
}
return n * getFactorial(n - 1);
}
public static void main(String[] args) {
int result = getFactorial(5);
System.out.println(result);
}
}
|
cs |
✍️ 거듭제곱 제곱 구하기
- 2^5을 출력하시오.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class RecursiveCall {
public static int pow(int n) {
if (n < 1) {
return 1;
}
return 2 * pow(n - 1);
}
public static void main(String[] args) {
int result = pow(5);
System.out.println(result);
}
}
|
cs |
✍️ 각 자릿수의 합
- 12321 각 자릿수의 합을 출력하시오.(예 1 + 2 + 3 + 2 + 1 = 9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class RecursiveCall {
public static int getResult(int n) {
if ( n <= 0 ) {
return (n % 10);
}
return getResult( n/10 ) + (n % 10);
}
public static void main(String[] args) {
int result = getResult(12321);
System.out.println(result);
}
}
|
cs |
🎯 과제
1) 팰린드롬1
https://www.acmicpc.net/problem/8892
2) 팰린드롬2
https://www.acmicpc.net/problem/10174
3) 콜라 문제
https://school.programmers.co.kr/learn/courses/30/lessons/132267
반응형
'교육 > 알고리즘_기본' 카테고리의 다른 글
📌 문자열 (0) | 2024.07.25 |
---|---|
📌 자료구조 : Set, Map (0) | 2024.07.18 |
📌 배열(개념) (0) | 2024.07.11 |
📌 자료구조 : 스택, 큐, 덱 (0) | 2024.07.01 |
📌 배열(문제집) (0) | 2024.06.26 |