Subset Sum Problem (Recursive Solution)

PHOTO EMBED

Sun Feb 06 2022 22:16:26 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #recursion #subsetsum

// Naive recursive solution : Time Complexity : Θ(2^n)

import java.io.*;
import java.util.*;

class GFG {

	static int countSubsets(int arr[], int n, int sum)
	{
		if(n == 0)
			return sum==0 ? 1 : 0;

		return countSubsets(arr, n-1, sum) + countSubsets(arr, n-1, sum - arr[n-1]);
	}

	public static void main (String[] args) 
    {
		int n = 3, arr[]= {10, 20, 15}, sum = 25;

		System.out.println(countSubsets(arr, n, sum));
	}
}
content_copyCOPY

Subsets of [1,2,3] are [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3] Example 1: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 9 Output: 1 Explanation: Here there exists a subset with sum = 9, 4+3+2 = 9. Example 2: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 30 Output: 0 Explanation: There is no subset with sum 30.