Skip to main content



      Home
Home » Language IDEs » Java Development Tools (JDT) » Subset Sum Problem in Java
Subset Sum Problem in Java [message #1860679] Fri, 25 August 2023 00:06 Go to next message
Eclipse UserFriend
Hi everyone,

I am working on the Subset Sum Problem in Java. I have found a solution using a recursive approach, but I am wondering if there is a more efficient way to solve it.

The problem is defined as follows:

Given an array of non-negative integers and an integer sum, find whether any subset exists in an array whose sum equals the given integer sum.
For example, given the array [1, 2, 3, 4, 5] and the sum 10, there are two possible subsets that satisfy the problem: [1, 5] and [2, 3, 4].

Here is my recursive solution in Java:
def subset_sum(set, n, sum):
if sum == 0:
return True
if n == 0:
return False
if set[n - 1] > sum:
return subset_sum(set, n - 1, sum)
return subset_sum(set, n - 1, sum) or subset_sum(set, n - 1, sum - set[n - 1])

This solution works, but it is not very efficient. Can anyone suggest a more efficient way to solve the Subset Sum Problem in Java?

Thanks in advance for your help!

Sources:
https://www.interviewbit.com/blog/subset-sum-problem/
https://github.com/aravindhrs-lab/ADA-1BM18CS145
Re: Subset Sum Problem in Java [message #1861050 is a reply to message #1860679] Fri, 15 September 2023 10:27 Go to previous message
Eclipse UserFriend
This really isn't the place for programming questions, it's for questions about the Java IDE. You'd have a better, more general, audience on javaranch.com or stackoverflow.com.
Previous Topic:Eclipse 2023-09 IDE for Java Developers Installation
Next Topic:Feature Request: Warn when there is an if statement with empty body
Goto Forum:
  


Current Time: Sun Jul 13 12:19:42 EDT 2025

Powered by FUDForum. Page generated in 0.25187 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top