본문 바로가기
Algorithm/LeetCode

💯 Daily LeetCode Challenge Day_11 - Subsets

by HaningYa 2020. 7. 12.
728x90

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com


문제

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],
  []
]

순서 상관없는 조합을 구하는 문제이다.

여기서 정리해놨다.

 

Java 중복유무 순열 조합

import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class main { static int[] arr = {1, 2, 3, 4}; public static void main(String[] args) { int n = arr.length; //순..

haningya.tistory.com

재귀함수로 구현했다.

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

댓글