首页 > 其他 > 详细

Factor Combinations

时间:2016-08-05 06:35:56      阅读:203      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!