赞
踩
题目:https://leetcode-cn.com/problems/partition-equal-subset-sum/
写题过程:一开始想的是先排序,再从中间位置寻找两边是否相等,可是想了想,不行,很容易推翻,最后去看力扣题解学习了一波
算法主体:
源代码:
class Solution { public: bool canPartition(vector<int>& nums) { int n = nums.size(); if(n < 2){ return false; } int total = 0; int max_t = INT_MIN; for(int t : nums){ total += t; max_t = max(max_t, t); } if(total % 2 == 1){ return false; } int target = total / 2; if(target < max_t){ return false; } vector<vector<bool>> dp(n,vector<bool>(target + 1,false)); for(int i = 0; i < n; ++i){ dp[i][0] = true; } dp[0][nums[0]] = true; for(int i = 1; i < n; ++i){ for(int j = 1; j < target + 1; ++j){ if(j >= nums[i]){ dp[i][j] = dp[i - 1][j] | dp[i - 1][j - nums[i]]; } else{ dp[i][j] = dp[i - 1][j]; } } } return dp[n - 1][target]; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。