Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Subsets II

Posted on January 20, 2018July 26, 2020 by braindenny

Subsets II



Similar Problems:

  • LeetCode: Letter Tile Possibilities
  • LeetCode: Letter Case Permutation
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #subset, #backtracking, #dfs, #classic

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/subsets-ii
// Basic Ideas: dfs + backtracking
//
//  No need to use hashmap
//
// Complexity: Time O(pow(2, n)), Space O(pow(2, n))
import "sort"
func dfs(combination []int, nums []int, pos int, res *[][]int) {
    combination2 := make([]int, len(combination))
    copy(combination2, combination)
    *res = append(*res, combination2)

    for i:=pos; i<len(nums); i++ {
        if i>pos && nums[i] == nums[i-1] { continue }
        combination = append(combination, nums[i])
        dfs(combination, nums, i+1, res)
        combination = combination[0:len(combination)-1]
    }
}

func subsetsWithDup(nums []int) [][]int {
    res := [][]int{}
    sort.Ints(nums)
    dfs([]int{}, nums, 0, &res)
    return res
}
linkedin
github
slack

Post Views: 4
Posted in MediumTagged #backtracking, #codetemplate, #combination, subset

Post navigation

LeetCode: Maximum XOR of Two Numbers in an Array
LeetCode: Unique Binary Search Trees

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.