Subset Sums in java by recursion
Input : arr[] = {2, 3}
Output: 0 2 3 5
Input : arr[] = {2, 4, 5}
Output : 0 2 4 5 6 7 9 11
import java.util.*;
import java.lang.*;
import java.io.*;
class abcs
{ public static ArrayList<Integer> treemap=new ArrayList<Integer>();
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
treemap.clear();
int x=ab.nextInt();
int arr[]=new int[x];
for(int o=0;o<x;++o)
{
arr[o]=ab.nextInt();
}
check(arr,x,0,0);
Collections.sort(treemap);
Iterator itr=treemap.iterator();
while(itr.hasNext())
System.out.print(itr.next()+" ");
System.out.println("");
}
}
public static void check(int a[],int n,int sum,int l)
{
if(l==n)
{
treemap.add(sum);
return;
}
check(a,n,sum,l+1);
check(a,n,sum+a[l],l+1);
}
}
Output: 0 2 3 5
Input : arr[] = {2, 4, 5}
Output : 0 2 4 5 6 7 9 11
import java.util.*;
import java.lang.*;
import java.io.*;
class abcs
{ public static ArrayList<Integer> treemap=new ArrayList<Integer>();
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
treemap.clear();
int x=ab.nextInt();
int arr[]=new int[x];
for(int o=0;o<x;++o)
{
arr[o]=ab.nextInt();
}
check(arr,x,0,0);
Collections.sort(treemap);
Iterator itr=treemap.iterator();
while(itr.hasNext())
System.out.print(itr.next()+" ");
System.out.println("");
}
}
public static void check(int a[],int n,int sum,int l)
{
if(l==n)
{
treemap.add(sum);
return;
}
check(a,n,sum,l+1);
check(a,n,sum+a[l],l+1);
}
}
0 Comments:
Post a Comment