forked from antimatter007/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 416.Partition-Equal-Subset-Sum_dfs_v2.cpp
- Loading branch information
1 parent
10a5112
commit 6e3ba1c
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
32 changes: 32 additions & 0 deletions
32
Dynamic_Programming/416.Partition-Equal-Subset-Sum/416.Partition-Equal-Subset-Sum_dfs_v2.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
class Solution { | ||
unordered_set<int>visited; | ||
public: | ||
bool canPartition(vector<int>& nums) | ||
{ | ||
int sum = accumulate(nums.begin(), nums.end(), 0); | ||
if (sum%2!=0) return false; | ||
return dfs(nums, sum/2, 0, 0); | ||
} | ||
|
||
bool dfs(vector<int>& nums, int targetSum, int i, int sum) | ||
{ | ||
int hash = sum * 20005 + i; | ||
if (visited.find(hash)!=visited.end()) | ||
return false; | ||
|
||
if (sum== targetSum) | ||
return true; | ||
|
||
if (sum> targetSum) | ||
return false; | ||
|
||
if (i == nums.size()) | ||
return false; | ||
|
||
if (dfs(nums, targetSum, i + 1, sum+ nums[i]) || dfs(nums, targetSum, i + 1, sum)) | ||
return true; | ||
|
||
visited.insert(hash); | ||
return false; | ||
} | ||
}; |