//Java implementation for subset sum
// problem using tabulation
import java.util.*;
class GfG {
// Function to check if there is a subset of arr[]
// with sum equal to the given sum using tabulation
static boolean isSubsetSum(int[] arr, int sum) {
int n = arr.length;
// Create a 2D array for storing results of
// subproblems
boolean[][] dp = new boolean[n + 1][sum + 1];
// If sum is 0, then answer is true
// (empty subset)
for (int i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
}
else {
// Include or exclude
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
public static void main
(String[] args
) {
int[] arr = { 3, 34, 4, 12, 5, 2 };
int sum = 9;
if (isSubsetSum(arr, sum)) {
}
else {
}
}
}
Ly9KYXZhIGltcGxlbWVudGF0aW9uIGZvciBzdWJzZXQgc3VtCi8vIHByb2JsZW0gdXNpbmcgdGFidWxhdGlvbgppbXBvcnQgamF2YS51dGlsLio7CgpjbGFzcyBHZkcgewoKICAgIC8vIEZ1bmN0aW9uIHRvIGNoZWNrIGlmIHRoZXJlIGlzIGEgc3Vic2V0IG9mIGFycltdCiAgICAvLyB3aXRoIHN1bSBlcXVhbCB0byB0aGUgZ2l2ZW4gc3VtIHVzaW5nIHRhYnVsYXRpb24KICAgICAgIHN0YXRpYyBib29sZWFuIGlzU3Vic2V0U3VtKGludFtdIGFyciwgaW50IHN1bSkgewogICAgICAgIGludCBuID0gYXJyLmxlbmd0aDsKCiAgICAgICAgLy8gQ3JlYXRlIGEgMkQgYXJyYXkgZm9yIHN0b3JpbmcgcmVzdWx0cyBvZgogICAgICAgIC8vIHN1YnByb2JsZW1zCiAgICAgICAgYm9vbGVhbltdW10gZHAgPSBuZXcgYm9vbGVhbltuICsgMV1bc3VtICsgMV07CgogICAgICAgIC8vIElmIHN1bSBpcyAwLCB0aGVuIGFuc3dlciBpcyB0cnVlCiAgICAgICAgICAvLyAoZW1wdHkgc3Vic2V0KQogICAgICAgIGZvciAoaW50IGkgPSAwOyBpIDw9IG47IGkrKykgewogICAgICAgICAgICBkcFtpXVswXSA9IHRydWU7CiAgICAgICAgfQoKICAgICAgICAvLyBGaWxsIHRoZSBkcCB0YWJsZSBpbiBib3R0b20tdXAgbWFubmVyCiAgICAgICAgZm9yIChpbnQgaSA9IDE7IGkgPD0gbjsgaSsrKSB7CiAgICAgICAgICAgIGZvciAoaW50IGogPSAxOyBqIDw9IHN1bTsgaisrKSB7CiAgICAgICAgICAgICAgICBpZiAoaiA8IGFycltpIC0gMV0pIHsKICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgLy8gRXhjbHVkZSB0aGUgY3VycmVudCBlbGVtZW50CiAgICAgICAgICAgICAgICAgICAgZHBbaV1bal0gPSBkcFtpIC0gMV1bal07CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgLy8gSW5jbHVkZSBvciBleGNsdWRlCiAgICAgICAgICAgICAgICAgICAgZHBbaV1bal0gPSBkcFtpIC0gMV1bal0KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHx8IGRwW2kgLSAxXVtqIC0gYXJyW2kgLSAxXV07CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIHJldHVybiBkcFtuXVtzdW1dOwogICAgfQoKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKICAgICAgCiAgICAgICAgaW50W10gYXJyID0geyAzLCAzNCwgNCwgMTIsIDUsIDIgfTsKICAgICAgICBpbnQgc3VtID0gOTsKCiAgICAgICAgaWYgKGlzU3Vic2V0U3VtKGFyciwgc3VtKSkgewogICAgICAgICAgICBTeXN0ZW0ub3V0LnByaW50bG4oIlRydWUiKTsKICAgICAgICB9CiAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiRmFsc2UiKTsKICAgICAgICB9CiAgICB9Cn0=