Perfect sums is the sum of two or more number of elements of arrays whose sum is equal to a given number. Return 999 if not found.
my method signature is:
public static int persfectSum(int arr[], int input)
For example:
arr={2,3,5,6,8,10}
input = 10;
5+2+3= 10
2+8 = 10
So, the output is 2;
It is a variation of Subset-Sum problem - with an additional constraint on the size of the subset (larger then 1).
The problem is NP-Complete , but for relatively small integers can be solved using Dynamic Programming in pseudo-polynomial time .
A possibly simpler alternative which is feasible for small arrays is brute-force - just search all possible subsets, and verify for each if it matches the sum.
I believe these guidelines are more then enough as a starter for you to start programming the problem and solve your problem (HW?) on your own.
Good luck.
int PerfectSums(int n, int a[], int sum)
{
int dp[n + 1][sum + 1] ;
dp[0][0] = 1;
for (int i = 1; i <= sum; i++)
dp[0][i] = 0;
for (int i = 1; i <= n; i++)
dp[i][0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if (a[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else
{
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - a[i - 1]];
}
}
}
return (dp[n][sum] == 0 ? 999 : dp[n][sum] ) ;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.