Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Permutations II

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

Permutations II



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #combination, #backtracking

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Github: code.dennyzhang.com

Credits To: leetcode.com

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


// https://code.dennyzhang.com/permutations-ii
// Basic Ideas: backtracking
//
// Complexity: Time O(n!), Space O(1)
import "sort"

func dfs(combination []int, visited []bool, nums []int, res *[][]int) {
    if len(combination) == len(nums) {
        combination2 := make([]int, len(combination))
        copy(combination2, combination)
        *res = append(*res, combination2)
        return
    }

    for i, b := range visited {
        if b { 
            continue
        }
        // avoid duplicated caculation
        if i>0 && nums[i-1] == nums[i] && ! visited[i-1] {
            continue
        }
        combination = append(combination, nums[i])
        visited[i] = true
        dfs(combination, visited, nums, res)
        visited[i] = false
        combination = combination[0:len(combination)-1]
    }
}

func permuteUnique(nums []int) [][]int {
    sort.Ints(nums)        
    res := [][]int{}
    visited := make([]bool, len(nums))
    dfs([]int{}, visited, nums, &res)
    return res
}
linkedin
github
slack

Post Views: 2
Posted in BasicTagged #backtracking, #combination, #inspiring

Post navigation

LeetCode: Partition List
LeetCode: Reverse Words in a String

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.