Main
calculate
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Scanner num = new Scanner(System.in);
static int N = num.nextInt();
static int answer = 0;
public static void main(String[] args) {
int[] nList = new int[N];
for(int i=0; i<N; i++) {
nList[i] = num.nextInt();
}
int c = 1;
calculate(nList[0], nList, c);
System.out.println(answer);
}
public static void calculate(int result, int[] nList, int i) {
int result1 = result+nList[i];
int result2 = result-nList[i];
i++;
if(0 <= result1 && result1 <= 20) {
if(i==(N-1)) {
if(result1==nList[N-1]) answer+= 1;
}
else calculate(result1, nList, i);
}
if(0 <= result2 && result2 <= 20) {
if(i==(N-1)) {
if(result2==nList[N-1]) answer += 1;
}
else calculate(result2, nList, i);
}
}
}
DP(Dynamic Programming)
: 큰 문제를 작은 단위로 쪼개 그 결과를 저장 후 재활용하여 답을 도출
- DP의 사용 조건
1) Overlapping Subproblems : 같은 계산이 중복됨
2) Optimal Substructure : 부분 문제의 결과가 전체 문제의 최적 답임
Main
calculate
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Scanner num = new Scanner(System.in);
static int N = num.nextInt();
public static void main(String[] args) {
int[] nList = new int[N];
int[][] result = new int[N][21];
for(int i=0; i<N; i++) {
nList[i] = num.nextInt();
}
result[0][nList[0]] = 1;
calculate(result, nList);
System.out.println(result[N-2][nList[N-1]]);
}
public static void calculate(int[][] result, int[] nList) {
for(int c=1; c<N-1; c++) {
for(int i=0; i<21; i++) {
if(result[c-1][i] > 0) {
if((i+nList[c])<=20) {
result[c][i+nList[c]] += result[c-1][i];
}
if(0<=(i-nList[c])) {
result[c][i-nList[c]] += result[c-1][i];
}
}
}
}
}
}
Long vs long
- Long
- 참조 타입 : 메모리 주소 값을 통해 객체를 참조
- null 값을 가질 수 있음 (기본 값 = null)
- id 값으로 자주 쓰임
- long
- 원시 타입 : 실제 메모리에 데이터를 직접 저장
- null 값을 가질 수 없음 (기본 값 = 0)
int vs long
- int
- 정수 (32bit)
- -2147483648 ~ 2147483647
- long
- 정수 (64bit)
- -9223372036854775808 ~ 9223372036854775807
- int에 비해 메모리 많이 차지함 , 느림
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Scanner num = new Scanner(System.in);
static int N = num.nextInt();
public static void main(String[] args) {
int[] nList = new int[N];
long[][] result = new long[N][21];
for(int i=0; i<N; i++) {
nList[i] = num.nextInt();
}
result[0][nList[0]] = 1;
calculate(result, nList);
System.out.println(result[N-2][nList[N-1]]);
}
public static void calculate(long[][] result, int[] nList) {
for(int c=1; c<N-1; c++) {
for(int i=0; i<21; i++) {
if(result[c-1][i] > 0) {
if((i+nList[c])<=20) {
result[c][i+nList[c]] += result[c-1][i];
}
if(0<=(i-nList[c])) {
result[c][i-nList[c]] += result[c-1][i];
}
}
}
}
}
}
