728x90
문제
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
순서 상관없는 조합을 구하는 문제이다.
여기서 정리해놨다.
재귀함수로 구현했다.
class Solution {
var answer : [[Int]] = []
var arr : [Int] = []
func subsets(_ nums: [Int]) -> [[Int]] {
var n = nums.count
arr = nums
// print(n)
for r in 0...n {
var reComArr = Array(repeating: 0, count: r)
reCombination(reComArr, n, r, 0, 0)
}
return answer
}
func reCombination(_ reComArr : [Int], _ n : Int, _ r :Int, _ index : Int, _ target : Int) {
var reComArr = reComArr
var tmp : [Int] = []
if r == 0 {
for i in reComArr {
// print(i)
// print(arr[i], terminator: "")
tmp.append(arr[i])
}
answer.append(tmp)
return
}
if target == n {return}
reComArr[index] = target
reCombination(reComArr, n, r - 1, index + 1, target + 1)
reCombination(reComArr, n, r, index, target + 1)
}
}
728x90
'Algorithm > LeetCode' 카테고리의 다른 글
💯 Daily LeetCode Challenge Day_13 - Same Tree (0) | 2020.07.13 |
---|---|
💯 Daily LeetCode Challenge Day_12 - Reverse Bits (0) | 2020.07.12 |
💯 Daily LeetCode Challenge Day_10 - Flatten a Multilevel Doubly Linked List (0) | 2020.07.10 |
💯 Daily LeetCode Challenge Day_09 - Maximum Width of Binary Tree (0) | 2020.07.09 |
💯 Daily LeetCode Challenge Day_08 - 3Sum (0) | 2020.07.09 |
댓글