Given an array of numbers check whether there exists a subset whose sum is equal to the target.
I wrote the following code and I am getting NullPointer Exception. I need help to figure out what is wrong with this.
"""
public class Main {
public static void main(String[] args) {
int arr[] = {1,2,3};
int n = arr.length;
int target = 4;
System.out.println(subsetSum(arr,target,0,0,new Boolean[n+1][target+1]));
}
public static Boolean subsetSum(int arr[] , int target , int index, int sum, Boolean dp[][]){
if(index == arr.length){
return false;
}
if(sum == target){
return true;
}
if(dp[index][sum]){
return dp[index][sum];
}
if(arr[index] + sum > target){
dp[index][sum] = subsetSum(arr,target,index+1,sum,dp);
return dp[index][sum];
}
dp[index][sum] = subsetSum(arr,target, index +1 , sum + arr[index],dp) ||
subsetSum(arr,target,index+1,sum,dp);
return dp[index][sum];
}}
"""