mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add solution2
This commit is contained in:
parent
e42c603dfd
commit
90575b6745
@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
|
|
||||||
## 思路二
|
## 思路二
|
||||||
其实本题也可以看做是一个01背包问题,改天对背包问题做个总结,先占个坑。
|
其实本题也可以看做是一个恰好装满的01背包问题,我在我的博客文章[动态规划之背包问题系列](https://tangshusen.me/2019/11/24/knapsack-problem/)对常见的几类背包问题做了个总结,此题的分析见5.1节,这里只给出代码。
|
||||||
|
|
||||||
|
|
||||||
# C++
|
# C++
|
||||||
@ -30,3 +30,21 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 思路二
|
||||||
|
``` C++
|
||||||
|
bool canPartition(vector<int>& nums) {
|
||||||
|
int sum = 0, n = nums.size();
|
||||||
|
for(int &num: nums) sum += num;
|
||||||
|
if(sum % 2) return false;
|
||||||
|
|
||||||
|
int capacity = sum / 2;
|
||||||
|
vector<bool>dp(capacity + 1, false);
|
||||||
|
dp[0] = true;
|
||||||
|
for(int i = 1; i <= n; i++)
|
||||||
|
for(int j = capacity; j >= nums[i-1]; j--)
|
||||||
|
dp[j] = dp[j] || dp[j - nums[i-1]];
|
||||||
|
|
||||||
|
return dp[capacity];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user