Skip to content

Commit b6b62b7

Browse files
committed
Add solution #254
1 parent 1781b76 commit b6b62b7

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@
243243
251|[Flatten 2D Vector](./solutions/0251-flatten-2d-vector.js)|Medium|
244244
252|[Meeting Rooms](./solutions/0252-meeting-rooms.js)|Easy|
245245
253|[Meeting Rooms II](./solutions/0253-meeting-rooms-ii.js)|Medium|
246+
254|[Factor Combinations](./solutions/0254-factor-combinations.js)|Medium|
246247
257|[Binary Tree Paths](./solutions/0257-binary-tree-paths.js)|Easy|
247248
258|[Add Digits](./solutions/0258-add-digits.js)|Easy|
248249
260|[Single Number III](./solutions/0260-single-number-iii.js)|Medium|

solutions/0254-factor-combinations.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 254. Factor Combinations
3+
* https://leetcode.com/problems/factor-combinations/
4+
* Difficulty: Medium
5+
*
6+
* Numbers can be regarded as the product of their factors.
7+
*
8+
* For example, 8 = 2 x 2 x 2 = 2 x 4.
9+
*
10+
* Given an integer n, return all possible combinations of its factors. You may return the
11+
* answer in any order.
12+
*
13+
* Note that the factors should be in the range [2, n - 1].
14+
*/
15+
16+
/**
17+
* @param {number} n
18+
* @return {number[][]}
19+
*/
20+
var getFactors = function(n) {
21+
const result = [];
22+
findFactors(n, 2, []);
23+
return result;
24+
25+
function findFactors(currentNum, start, combination) {
26+
for (let i = start; i * i <= currentNum; i++) {
27+
if (currentNum % i === 0) {
28+
const nextNum = currentNum / i;
29+
if (nextNum >= i && nextNum < currentNum) {
30+
result.push([...combination, i, nextNum]);
31+
findFactors(nextNum, i, [...combination, i]);
32+
}
33+
}
34+
}
35+
}
36+
};

0 commit comments

Comments
 (0)