Skip to content

Commit 63ea117

Browse files
committed
0/1 Knapsack using Tabulation method
1 parent d6551df commit 63ea117

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Dynamic Programming/knapsack_01.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,28 @@ class Solution
8585
}
8686
};
8787

88+
89+
// Alternative Method for 0/1 Knapsack
90+
//Tabulation Method (Bottom-up Approach)
91+
//Function to return max value that can be put in knapsack of capacity W.
92+
int knapSack(int W, int wt[], int val[], int n)
93+
{
94+
// Your code here
95+
int dp[n+1][W+1];
96+
for(int i=0;i<n+1;i++)
97+
{
98+
for(int j=0;j<W+1;j++)
99+
if(i==0 || j==0)
100+
dp[i][j]=0;
101+
else if(wt[i-1]<=j)
102+
dp[i][j]= max(val[i-1] + dp[i-1][j-wt[i-1]] , dp[i-1][j]);
103+
else
104+
dp[i][j]= dp[i-1][j];
105+
}
106+
return dp[n][W];
107+
}
108+
109+
88110
// { Driver Code Starts.
89111

90112
int main()

0 commit comments

Comments
 (0)