,敢教日月换新天。为有牺牲多壮志

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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10225203.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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. Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
  2. You may assume that n is always positive.
  3. 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],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 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, 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 }
复制代码

 

posted @   为敢技术  阅读(272)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°