leetcode 416. Partition Equal Subset Sum 动态规划DP + DFS深度优先遍历

来源:互联网 发布:网络电视怎么搜索频道 编辑:程序博客网 时间:2024/05/05 15:45

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

这道题可以使用DFS来做,但是可能超时,我想到了使用DP动态规划,但是忘记又该怎么做了,这道题又一次给了一个警醒,DP动态规划真的是很难得,不过本题还是很简单了的dp[i]表示和为i是否可以被满足

本题建议和leetcode 698. Partition to K Equal Sum Subsets K个子集 + 深度优先搜索DFS 一起学习

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>using namespace std;class Solution {public:    bool canPartition(vector<int>& nums)     {        int sum = 0;        for (int a : nums)            sum += a;        if (sum % 2 != 0)            return false;        int target = sum / 2;        vector<bool>dp (target + 1, 0);        dp[0] = true;        for (int i = 0; i < nums.size(); i++)        {            for (int j = target; j>= nums[i]; j--)                dp[j] = dp[j]|| dp[j-nums[i]];        }        return dp[target];    }};
阅读全文
0 0