Hi,
I am providing the solution of Partition Problem here. My score in the contest is 100 in java, if you have any better solution of this problem, feel free to share it.
Download Link : Code
Download link : Code
public class Partition {
/**
* @param args
*/
public static final String yes = "Yes";
public static final String no = "No";
public static final String invalid = "Invalid";
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {1, 5, 11,5};
System.out.println(findPartiion(arr,4));
}
// A utility function that returns true if there is a subset of arr[]
// with sun equal to given sum
public static boolean isSubsetSum (int arr[], int n, int sum)
{
System.out.println(n+" "+sum);
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element
*/
return isSubsetSum (arr, n-1, sum) || isSubsetSum (arr, n-1, sum-arr[n-1]);
}
// Returns true if arr[] can be partitioned in two subsets of
// equal sum, otherwise false
public static String findPartiion (int arr[], int n)
{
// Calculate sum of the elements in array
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
if(arr[i]<0)
return invalid;
}
// If sum is odd, there cannot be two subsets with equal sum
if (sum%2 != 0)
return no;
// Find if there is subset with sum equal to half of total sum
boolean b = isSubsetSum (arr, n, sum/2);
if(b)
return yes;
else
return no;
}
}Download Link : Code
Download link : Code

0 comments:
Post a Comment