diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" index d18ad79e1d2db..95a8fabffb8e4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" @@ -156,6 +156,28 @@ func canPartition(nums []int) bool { } ``` +#### Swift + +```swift +class Solution { + func canPartition(_ nums: [Int]) -> Bool { + let s = nums.reduce(0, +) + if s % 2 != 0 { return false } + let target = s / 2 + var dp = Array(repeating: false, count: target + 1) + dp[0] = true + + for num in nums { + for j in stride(from: target, through: num, by: -1) { + dp[j] = dp[j] || dp[j - num] + } + } + + return dp[target] + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.swift" new file mode 100644 index 0000000000000..b6eda6e15b417 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/Solution.swift" @@ -0,0 +1,17 @@ +class Solution { + func canPartition(_ nums: [Int]) -> Bool { + let s = nums.reduce(0, +) + if s % 2 != 0 { return false } + let target = s / 2 + var dp = Array(repeating: false, count: target + 1) + dp[0] = true + + for num in nums { + for j in stride(from: target, through: num, by: -1) { + dp[j] = dp[j] || dp[j - num] + } + } + + return dp[target] + } +} \ No newline at end of file