Subset Sum with target - Coding Interview Question

Mani
Mani
Educating everyone with the beauty of programming!!
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given target sum.
Example:

Input:  set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output:  True  //There is a subset (4, 5) with sum 9.

Reference: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/


Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class SubsetSumWithTarget {

    static boolean checkIfSubsetExistsWithTargetSum(int[] w, int c) {
        boolean[][] dp = new boolean[w.length + 1][c + 1];
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = true;
        }

        for (int i = 1; i <= w.length; i++) {
            for (int j = 1; j <= c; j++) {
                if (w[i - 1] <= j) {
                    dp[i][j] = dp[i - 1][j - w[i - 1]] || dp[i - 1][j];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        return dp[w.length][c];
    }

    public static void main(String[] args) {
        int[] w = {3, 34, 4, 12, 5, 2};
        int c = 9;
        System.out.println(checkIfSubsetExistsWithTargetSum(w, c));

        int[] w1 = {3, 34, 4, 12, 5, 2};
        int c1 = 13;
        System.out.println(checkIfSubsetExistsWithTargetSum(w1, c1));
    }
}
Drop your comments below for any questions or comments. For full list of must learn top interview questions Click Here: Must Learn Top Interview Questions

Rating: