Leetcode 254: Factor Combinations

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.

 

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]
]

 

 

 

 1 public class Solution {
 2     public IList<IList<int>> GetFactors(int n) {
 3         var results = new List<IList<int>>();
 4         DFS(n, new List<int>(), results);
 5         return results;
 6     }
 7     
 8     private void DFS(int cur, IList<int> candidate, IList<IList<int>> results)
 9     {
10         int start = candidate.Count == 0 ? 2 : candidate[candidate.Count - 1];
11         for (int i = start; i <= Math.Sqrt(cur); i++)
12         {
13             if (cur % i == 0)
14             {
15                 var tmp = new List<int>(candidate);
16                 tmp.Add(i);
17                 tmp.Add(cur / i);
18                 results.Add(tmp);
19 
20                 // can further split
21                 if (cur / i >= 4)
22                 {
23                     candidate.Add(i);
24                     DFS(cur / i, candidate, results);
25                     candidate.RemoveAt(candidate.Count - 1);
26                 }
27             }
28         }
29     }
30 }

 

posted @ 2017-12-19 05:11  逸朵  阅读(124)  评论(0编辑  收藏  举报