forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPartitionEqualSubsetSum.java
More file actions
32 lines (28 loc) · 867 Bytes
/
PartitionEqualSubsetSum.java
File metadata and controls
32 lines (28 loc) · 867 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class PartitionEqualSubsetSum {
// TC : O(n*m) , where n is the totalSum/2, m is num of elements in input array
public boolean canPartition(int[] nums) {
int totalSum = 0;
for(int el: nums){
totalSum += el;
}
if(totalSum%2 !=0){
return false;
}
totalSum = totalSum/2;
boolean[][] dp = new boolean[nums.length +1][totalSum+1];
for(int i=0;i<=nums.length;i++){
dp[i][0] = true;
}
for(int i =1;i<=nums.length;i++){
for(int j=1;j<=totalSum;j++){
dp[i][j] = dp[i-1][j];
if(!dp[i-1][j]) {
if(j >= nums[i-1]){
dp[i][j] = dp[i-1][j - nums[i-1]];
}
}
}
}
return dp[nums.length][totalSum];
}
}