[Swift]LeetCode254.因子组合 $ Factor Combinations

[Swift]LeetCode254.因子组合 $ Factor Combinations,第1张

概述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:  Each c

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: 

Each combination‘s factors must be sorted ascending,for example: The factors of 2 and 6 is [2,6],not [6,2]. You may assume that n is always positive. Factors should be greater than 1 and less than n.

Examples: 
input: 1
output: 

[]

input: 37
output: 

[]

input: 12
output:

[  [2,6],[2,2,3],[3,4]]

input: 32
output:

[  [2,16],8],4],2],4,[4,8]]

数字可以被视为其因子的乘积。例如,

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

编写一个接受整数n并返回所有可能的因子组合的函数。

注:

每个组合的因子必须按升序排序,例如:2和6的因子是[2,6],而不是[6,2]。

你可以假设n总是正的。

系数应大于1且小于n。

实例:

输入:1

输出:

[]

输入:37

输出:

[]

输入:12

输出:

[  [2,4]]

输入:32

输出:

[  [2,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 = start13         while(i <= num)14         {15             if n % i == 016             {17                 var new_out:[Int] = out18                 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 += 124         }  25     }26 }
总结

以上是内存溢出为你收集整理的[Swift]LeetCode254.因子组合 $ Factor Combinations全部内容,希望文章能够帮你解决[Swift]LeetCode254.因子组合 $ Factor Combinations所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1021180.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存