New Solution "Partition Equal Subset Sum"

This commit is contained in:
Hao Chen 2018-06-25 23:17:33 +08:00
parent e8047e01f2
commit ef4f240d94
2 changed files with 66 additions and 0 deletions

View File

@ -13,6 +13,7 @@ LeetCode
|643|[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [C++](./algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp)|Easy|
|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium|
|418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) ♥ | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy|
|416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium|
|415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy|
|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy|
|413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium|

View File

@ -0,0 +1,65 @@
// Source : https://leetcode.com/problems/partition-equal-subset-sum/description/
// Author : Hao Chen
// Date : 2018-06-24
/***************************************************************************************
*
* 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.
*
***************************************************************************************/
class Solution {
public:
//back tracking
bool canPartitionRecrusion(vector<int>& nums, int half, int index) {
for (int i=index; i<nums.size(); i++){
int h = half - nums[i];
if ( h < 0 ) return false; //cannot found the solution
if ( h == 0 ) return true; //found the solution
if ( canPartitionRecrusion(nums, h, i+1) == true ) return true;
}
return false;
}
bool canPartition(vector<int>& nums) {
int sum = 0;
for(auto n : nums) sum +=n;
if ( sum & 1 ) return false; // sum % 2 != 1
int half = sum / 2;
//sort the array in descending order
//so, the DFS could be very fast to find the answer because it's greedy.
std::sort(nums.begin(), nums.end(), std::greater<int>());
//go to find a path which sum is half
return canPartitionRecrusion(nums, half, 0);
}
};