Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9fec3f6

Browse files
Merge pull request fnplus#324 from Aditya2603/patch-5
[Algorithm] Sum of Subset [Java]
2 parents 623f7a0 + f763249 commit 9fec3f6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎Algorithms/sumofsubset.java‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
class sumofsubset
5+
{
6+
// Return true if there exists a sub-array of array[0..n] with given sum
7+
public static boolean subsetSum(int[] A, int n, int sum)
8+
{
9+
// return true if sum becomes 0 (subset found)
10+
if (sum == 0) {
11+
return true;
12+
}
13+
14+
// base case: no items left or sum becomes negative
15+
if (n < 0 || sum < 0) {
16+
return false;
17+
}
18+
19+
// Case 1. include current item in the subset (A[n]) and recur
20+
// for remaining items (n - 1) with remaining sum (sum - A[n])
21+
boolean include = subsetSum(A, n - 1, sum - A[n]);
22+
23+
// Case 2. exclude current item n from subset and recur for
24+
// remaining items (n - 1)
25+
boolean exclude = subsetSum(A, n - 1, sum);
26+
27+
// return true if we can get subset by including or excluding the
28+
// current item
29+
return include || exclude;
30+
}
31+
32+
// Subset Sum Problem
33+
public static void main(String[] args)
34+
{
35+
// Input: set of items and a sum
36+
Scanner a = new Scanner(System.in);
37+
int n = a.nextInt();
38+
int sum = a.nextInt();
39+
int[] A = new int[n];
40+
for(int i=0;i<n;i++)
41+
A=a.nextInt();
42+
43+
if (subsetSum(A, A.length - 1, sum)) {
44+
System.out.print("Yes");
45+
}
46+
else {
47+
System.out.print("No");
48+
}
49+
}
50+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /