LeetCode-in-All

78. Subsets

Medium

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Example 1:

Input: nums = [1,2,3]

Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Example 2:

Input: nums = [0]

Output: [[],[0]]

Constraints:

Solution

defmodule Solution do
   @spec subsets(nums :: [integer]) :: [[integer]]
  def subsets(nums) do
    arr_lenth = length(nums)

    0..arr_lenth
    |> Enum.reduce([], fn x, acc ->
      Enum.concat(combinations(x, nums), acc)
    end)
    |> Enum.sort_by(&length/1)
  end

  def combinations(0, _), do: [[]]
  def combinations(_, []), do: []

  def combinations(size, [head | tail]) do
    for elem <- combinations(size - 1, tail) do
      [head | elem]
    end ++ combinations(size, tail)
  end
end