Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Factor Combinations

Posted on August 7, 2018July 26, 2020 by braindenny

Factor Combinations



Similar Problems:

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

Numbers can be regarded as product of its factors. For example,

8 = 2 x 2 x 2;
  = 2 x 4.

Write a function that takes an integer n and return all possible combinations of its factors.

Note:

  1. You may assume that n is always positive.
  2. Factors should be greater than 1 and less than n.

Example 1:

Input: 1
Output: []

Example 2:

Input: 37
Output:[]

Example 3:

Input: 12
Output:
[
  [2, 6],
  [2, 2, 3],
  [3, 4]
]

Example 4:

Input: 32
Output:
[
  [2, 16],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]

Github: code.dennyzhang.com

Credits To: leetcode.com

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


  • Solution:
// https://code.dennyzhang.com/factor-combinations
// Basic Ideas: backtracking
//
//   Key points: How to avoid duplicates
//
// Complexity: Time ? Space ?
import "math"
func dfs(combination []int, start int, n int, res *[][]int) {
    if (n == 1) && len(combination) > 1 {
        combination2 := make([]int, len(combination))
        copy(combination2, combination)
        *res = append(*res, combination2)
        return
    }

    for i:=start; i<=int(math.Sqrt(float64(n))); i++ {
        if (n%i==0) {
            combination = append(combination, i)
            dfs(combination, i, n/i, res)
            combination = combination[0:len(combination)-1]
        }
    }
    // examine myself
    if len(combination) != 0 {
        combination = append(combination, n)
        dfs(combination, n, 1, res)
        combination = combination[0:len(combination)-1]
    }
}

func getFactors(n int) [][]int {
    res := [][]int{}
    dfs([]int{}, 2, n, &res)
    return res
}
linkedin
github
slack

Post Views: 6
Posted in BasicTagged #backtracking, #recursive

Post navigation

LeetCode: UTF-8 Validation
LeetCode: Pyramid Transition Matrix

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.