Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //TC O(N*W) w=sum of whole array.
- //created a dp where column contains sum from 0 to total sum of array
- //and row contains elements of all the array,oth row means no elements selected
- //logic is simple,either include the curretn element or not
- class Solution {
- public:
- bool canPartition(vector<int>& arr) {
- int sum=0,n=arr.size();
- for(int i=0;i<n;i++) sum+=arr[i]; //found sum of all the items ie. j or column of dp aray
- if(sum%2!=0) return false;
- bool dp[n+1][sum+1];
- for(int i=0;i<=n;i++){
- for(int j=0;j<=sum;j++){
- if(j==0){dp[i][j]=true;} //0 weight is possible to have without including any item
- else if(i==0){dp[i][j]=false;} //all the weight from 1 to sum can't be possible with no items
- else if(arr[i-1]>j){ //if current array element is greater than the j weight,
- dp[i][j]=dp[i-1][j]; //then it can't be included.
- }
- else{ //if current array element is smaller than current weight,then either it can be included
- dp[i][j]=dp[i-1][j] || dp[i-1][j-arr[i-1]]; //or not incuded.
- }
- }
- }
- return dp[n][sum/2]; //check for half sum is possible or not?
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement