码迷,mamicode.com
首页 > 其他好文 > 详细

Factor Combinations

时间:2016-08-05 06:36:48      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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.
 1     public List<List<Integer>> getFactors(int n) {
 2         List<List<Integer>> listAll = new ArrayList<>();
 3         if (n < 2) return listAll;
 4 
 5         helper(n, 2, 1, listAll, new ArrayList<Integer>());
 6         return listAll;
 7     }
 8 
 9     public void helper(int n, int number, int value, List<List<Integer>> listAll, List<Integer> list) {
10         if (number > (n + 1) / 2 || value > n) return;
11         list.add(number);
12         value *= number;
13         
14         if (n == value) {
15             listAll.add(new ArrayList<Integer>(list));
16         }
17 
18         helper(n, number, value, listAll, list);
19         value /= number;
20         list.remove(list.size() - 1);
21         helper(n, number + 1, value, listAll, list);
22     }

 

Factor Combinations

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5739783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!