Created
August 3, 2019 23:22
-
-
Save piyush23dez/bb7539f1831853a60bdf292a144fc2e4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//The first intuition is figuring out the sum we are looking for is actually sum /2 and it should be even. | |
//Then, the next inuition is recognizing the problem converts to finding a subset with that sum. | |
func canPartition(_ nums: [Int]) -> Bool { | |
let total = nums.reduce(0,+) | |
if total%2 != 0 { | |
return false | |
} | |
return canPartition(nums, 0, 0, total) | |
} | |
func canPartition(_ nums: [Int], _ index: Int, _ sum: Int, _ total: Int) -> Bool { | |
if sum * 2 == total { | |
return true | |
} | |
if sum > total/2 || index >= nums.count { | |
return false | |
} | |
return canPartition(nums, index+1, sum, total) || | |
canPartition(nums, index+1, sum+nums[index], total) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment