Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created June 26, 2019 15:03
Show Gist options
  • Save yangpeng-chn/4ae823bee3f600f62b537ccc004f93ca to your computer and use it in GitHub Desktop.
Save yangpeng-chn/4ae823bee3f600f62b537ccc004f93ca to your computer and use it in GitHub Desktop.
0/1 Knapsack (Dynamic Programming)
bool canPartition(vector<int>& nums) {
const int sum = std::accumulate(nums.begin(), nums.end(), 0);
if(sum % 2 != 0) return false;
vector<bool> dp(sum+1, false);
dp[0] = true;
for( const int num : nums){
for(int i = sum; i >= 0; i--){
if(dp[i]) dp[i+num]=true;
}
if(dp[sum/2])
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment