diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" index eff8b96dd4837..517becb3dd51c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" @@ -266,6 +266,40 @@ class Comparer : IComparer> } ``` +#### Swift + +```swift +class Solution { + private var ans: [[Int]] = [] + private var candidates: [Int] = [] + private var target: Int = 0 + + func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { + self.ans = [] + self.target = target + self.candidates = candidates.sorted() + dfs(0, 0, []) + return ans + } + + private func dfs(_ index: Int, _ sum: Int, _ current: [Int]) { + if sum > target { + return + } + if sum == target { + ans.append(current) + return + } + for i in index.. index && candidates[i] == candidates[i - 1] { + continue + } + dfs(i + 1, sum + candidates[i], current + [candidates[i]]) + } + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/Solution.swift" new file mode 100644 index 0000000000000..acbf254fa8b79 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/Solution.swift" @@ -0,0 +1,29 @@ +class Solution { + private var ans: [[Int]] = [] + private var candidates: [Int] = [] + private var target: Int = 0 + + func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { + self.ans = [] + self.target = target + self.candidates = candidates.sorted() + dfs(0, 0, []) + return ans + } + + private func dfs(_ index: Int, _ sum: Int, _ current: [Int]) { + if sum > target { + return + } + if sum == target { + ans.append(current) + return + } + for i in index.. index && candidates[i] == candidates[i - 1] { + continue + } + dfs(i + 1, sum + candidates[i], current + [candidates[i]]) + } + } +} \ No newline at end of file