1. 1차원 dp[] 를 사용한 방법
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class 12865_평범한배낭 {
public static int N,K; // 물품의 수 N, 준서가 버틸 수 있는 무게 K
public static int dp[];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] str = br.readLine().split(" ");
N = Integer.parseInt(str[0]);
K = Integer.parseInt(str[1]);
dp = new int[K+1];
int w, v; // 물건의 무게 w, 물건의 가치 v;
for(int i =0; i<N; i++) {
str = br.readLine().split(" ");
w = Integer.parseInt(str[0]);
v = Integer.parseInt(str[1]);
int value, cost;
for(int j = K; j>=w; j--) {
value = j - w;
cost = v + dp[value];
if(cost > dp[j]) { // w의 가치 + w를 제외한 나머지 무게의 가치 > j의 가치
dp[j] = cost;
}
}
}
System.out.println(dp[K]);
}
}
2. 2차원 dp[][] 를 사용한 방법
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class 12865_평범한배낭 {
public static int N,K; // 물품의 수 N, 준서가 버틸 수 있는 무게 K
public static int dp[][];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] str = br.readLine().split(" ");
N = Integer.parseInt(str[0]);
K = Integer.parseInt(str[1]);
dp = new int[N+1][K+1];
int w, v; // 물건의 무게 w, 물건의 가치 v;
for(int i =1; i<=N; i++) {
str = br.readLine().split(" ");
w = Integer.parseInt(str[0]);
v = Integer.parseInt(str[1]);
for(int j=0; j<K+1; j++) {
dp[i][j] = dp[i-1][j];
}
int cost;
for(int j = K; j>=w; j--) {
cost = v + dp[i-1][j-w];
if(cost > dp[i-1][j]) {
dp[i][j] = cost;
}
}
}
System.out.println(dp[N][K]);
}
}
멋지다 박연진!