-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEqualSumPartition.java
51 lines (40 loc) · 1.16 KB
/
EqualSumPartition.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
// slight variation with subset sum ,
// if sum odd - > not possible
// if even - > check for sum/2 if it is true then obviously it will divide
public boolean canPartition(int[] nums) {
int sum = 0 ;
for(int a : nums) {
sum+=a;
}
if(sum %2 != 0) return false;
return isSubsetSum(nums.length , nums , sum /2);
}
static Boolean isSubsetSum(int N, int arr[], int sum){
boolean[][] dp = new boolean[N + 1][sum + 1];
// code here
for(int i=0;i<N+1;i++)
for(int j=0;j<sum+1;j++)
{
if(i==0)
dp[i][j]= false;
if(j==0)
dp[i][j]= true;
if(i==0&&j==0)
dp[i][j]=true;
}
for(int i=1;i<N+1;i++)
for(int j=1;j<sum+1;j++)
{
if(arr[i-1]<=j)
{
dp[i][j]= dp[i-1][j]||dp[i-1][j-arr[i-1]];
}
else if(arr[i-1]>j)
{
dp[i][j]= dp[i-1][j];
}
}
return dp[N][sum];
}
}