동적 계획법(DP) 공부하려고 문제들을 보니, 재귀 관련해서 내용이 많이 나오길래 재귀 먼저 한번 훑기로 했다.
단계별로 풀어보기 > 재귀 | 재귀 함수를 다뤄봅시다. https://www.acmicpc.net/step/19
27433. 팩토리얼2 https://www.acmicpc.net/problem/27433
브론즈5 | 수학
재귀 잘 모르고 짠 코드
import java.util.Scanner;
public class q27433 {
static int n;
static long ans=1; // long 타입 주의
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
fac(0);
System.out.println(ans);
}
static void fac(int x) {
if(x==n) return;
else {
x++;
ans *= (x);
fac(x);
}
}
}
다시 재귀로 짠 코드
import java.util.Scanner;
public class q27433_recur {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(fac(n));
}
static long fac(long x) {
if(x==0) return 1;
return x*fac(x-1);
}
}
10870. 피보나치 수 5 https://www.acmicpc.net/problem/10870
브론즈2 | 수학
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(fib(n));
}
static int fib(int x) {
if(x==0) return 0;
if(x==1) return 1;
return fib(x-1) + fib(x-2);
}
}
25501. 재귀의 귀재 https://www.acmicpc.net/problem/25501
브론즈2 | 구현
import java.util.Scanner;
public class Main {
static int cnt;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i=0; i<T; i++) {
String s = sc.next();
cnt=0;
System.out.println(isPalindrome(s, 0, s.length()-1) + " " + cnt);
}
}
static int isPalindrome(String s, int l, int r) {
cnt++;
if(r<=l) return 1;
else if(s.charAt(l) != s.charAt(r)) return 0;
else return isPalindrome(s, l+1, r-1);
}
}
[1일1커밋 8D] 아자아자 | 유형별 풀이(2) 이진탐색 ing | 백준 JAVA 1920, 10816 (0) | 2024.09.29 |
---|---|
[1일1커밋 7D] 연휴 끝! 다시 시작하는 1일1커밋 챌린지 | SWEA S/W 문제해결 기본 4일차 (3) | 2024.09.23 |
[1일1커밋 5D] LeetCode SQL & 백준 JAVA 10431, 8979, 7568, 4659 (1) | 2024.09.06 |
[1일1커밋 4D] LeetCode SQL & 백준 JAVA 11723, 9655 (비트 뭐시기와 DP) (2) | 2024.09.06 |
[1일1커밋 3D] LeetCode SQL & 백준 JAVA 23971, 5073, 2292, 7562 (수학.. 그래프 순회) (2) | 2024.09.04 |
댓글 영역