★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vkkqsgkm-mb.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Numbers can be regarded as product of its factors. For example,git
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.github
Note: 微信
[2, 6]
, not [6, 2]
.Examples:
input: 1
output: app
[]
input: 37
output: less
[]
input: 12
output:函數
[ [2, 6], [2, 2, 3], [3, 4] ]
input: 32
output:spa
[ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ]
數字能夠被視爲其因子的乘積。例如,code
8 = 2 x 2 x 2; = 2 x 4.
編寫一個接受整數n並返回全部可能的因子組合的函數。htm
注:
每一個組合的因子必須按升序排序,例如:2和6的因子是[2,6],而不是[6,2]。
你能夠假設n老是正的。
係數應大於1且小於n。
實例:
輸入:1
輸出:
[]
輸入:37
輸出:
[]
輸入:12
輸出:
[ [2, 6], [2, 2, 3], [3, 4] ]
輸入:32
輸出:
[ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ]
1 class Solution { 2 func getFactors(_ n:Int) -> [[Int]]{ 3 var res:[[Int]] = [[Int]]() 4 var arr:[Int] = [Int]() 5 helper(n,2,&arr,&res) 6 return res 7 } 8 9 func helper(_ n:Int,_ start:Int,_ out:inout [Int],_ res:inout [[Int]]) 10 { 11 var num:Int = Int(floor(sqrt(Double(n)))) 12 var i :Int = start 13 while(i <= num) 14 { 15 if n % i == 0 16 { 17 var new_out:[Int] = out 18 new_out.append(i) 19 helper(n / i, i, &new_out, &res) 20 new_out.append(n / i) 21 res.append(new_out) 22 } 23 i += 1 24 } 25 } 26 }