diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" index e35ccea2e7284..6cbbc0e15211d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" @@ -151,6 +151,35 @@ func dfs(i, n, k int, t []int, res *[][]int) { } ``` +#### Swift + +```swift +class Solution { + func combine(_ n: Int, _ k: Int) -> [[Int]] { + var res = [[Int]]() + dfs(1, n, k, [], &res) + return res + } + + private func dfs(_ start: Int, _ n: Int, _ k: Int, _ current: [Int], _ res: inout [[Int]]) { + if current.count == k { + res.append(current) + return + } + + if start > n { + return + } + + for i in start...n { + var newCurrent = current + newCurrent.append(i) + dfs(i + 1, n, k, newCurrent, &res) + } + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/Solution.swift" new file mode 100644 index 0000000000000..8fcd987d69701 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/Solution.swift" @@ -0,0 +1,24 @@ +class Solution { + func combine(_ n: Int, _ k: Int) -> [[Int]] { + var res = [[Int]]() + dfs(1, n, k, [], &res) + return res + } + + private func dfs(_ start: Int, _ n: Int, _ k: Int, _ current: [Int], _ res: inout [[Int]]) { + if current.count == k { + res.append(current) + return + } + + if start > n { + return + } + + for i in start...n { + var newCurrent = current + newCurrent.append(i) + dfs(i + 1, n, k, newCurrent, &res) + } + } +}