Equal Partition Sum Recursive Approach
import java.util.Scanner;
class KnapsackSolve{
public boolean knapsack(int[] arr, int n, int sum){
if(n==0 && sum==0){
return true;
}
if(n==0 && sum!=0){
return false;
}
if(sum==0){
return true;
}
else{
if(arr[n-1]>sum){
return knapsack(arr,n-1,sum);
}
else{
return (knapsack(arr,n-1,sum) || knapsack(arr,n-1,sum-arr[n-1]));
}
}
}
}
class EqualSumPartitionRecursive{
public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<n;i++){
sum=sum+arr[i];
}
if(sum%2!=0){
System.out.println("false");
System.out.println("Not possible");
}
else{
KnapsackSolve obj1=new KnapsackSolve();
boolean c=obj1.knapsack(arr,n,sum/2);
System.out.println(c);
}
}
}
Comments
Post a Comment