CS331 Advanced Data Structures – Spring 2016 Knapsack Problem , a

advertisement
CS331 Advanced Data Structures – Spring 2016
Knapsack Problem
The Problem : Given n value a1 , a2 , . . . , an and a knapsack size K, find a subset of values whose
sum is equal to K, i.e. a subset S where
X
ai = K
ai ∈S
The Recurrence Relation : Let Ci,k
k. Then


 true,



 false,
true,
Ci,k =






= true if there is a subset of the first i items that sums to
i = 0, k = 0,
i = 0, k > 0,
i > 0, k ≥ 0
i > 0, k ≥ ai
false, otherwise,
and Ci−1,k is true, or
and Ci−1,k−ai is true,
The Code :
boolean knapsack(int [] a, int K)
{
int n = a.length();
boolean [][] table = new boolean[K+1][n+1];
table[0][0] = true;
for(int k=1; k<=K; i++)
table[k][0] = false;
for(int i=1; i<=n; i++) {
for(int k=0; k<a[j]; k++)
table[k][i] = table[k][i-1];
for(int k=a[j]; k<=K; k++)
table[k][i] = table[k][i-1] || table[k-a[j]][i-1];
}
return table[K][n];
}
The Time Complexity : T (n) = O(nK) (but not polynomial in input size!).
Download