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:

  • 1 <= nums.length <= 10

  • -10 <= nums[i] <= 10

  • All the numbers of nums are unique.

解題

Runtime: 0 ms, faster than 100%

Memory Usage: 2.3 MB, less than 22.90%

func subsets(nums []int) [][]int {
    ans := make([][]int, 0)

    var dfs func(int, []int)
    dfs = func(index int, cur []int) {
        ans = append(ans, append([]int{}, cur...))

        if index >= len(nums) { return }

        for i:=index; i<len(nums); i++ {
            dfs(i + 1, append(cur, nums[i]))
        }
    }

    dfs(0, []int{})

    return ans
}

下面的方法也可以,但是比較慢

func subsets(nums []int) [][]int {
    ans := make([][]int, 0)

    var dfs func(int, []int)
    dfs = func(index int, cur []int) {
        if index == len(nums) {
            ans = append(ans, append([]int{}, cur...))
            return
        }

        dfs(index + 1, append(cur, nums[index])) //取該index的值
        dfs(index + 1, cur) //不取
    }

    dfs(0, []int{})

    return ans
}

Last updated