254. Factor Combinations

Source: Internet
Author: User

Topic:

Numbers can 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 are sorted ascending, for example:the factors of 2 and 6 [2, 6] are, not [6, 2] .
    2. You are assume that n are always positive.
    3. Factors should is greater than 1 and less than n.

Examples:
Input1
Output

[]
Input 37
Output
[]
Input 12
Output
[  [2, 6],  [2, 2, 3],  [3, 4]]
Input 32
Output
[  2, +],  [2, 2, 8], [  2, 2, 2, 4],  [2, 2, 2, 2, 2],  [2, 4, 4], [4  , 8]]

Links: http://leetcode.com/problems/factor-combinations/

Exercises

Ask for a number of all factor, here we think of the DFS + backtracking, it should be noted that factor are >= 2, and in this problem, the number itself can not be counted as factor, so we have when n <= 1 o'clock judgment if ( List.size () > 1) Add the result to Res.

Time Complexity-o (2n), Space complexity-o (n).

 Public classSolution { PublicList<list<integer>> Getfactors (intN) {List<List<Integer>> res =NewArraylist<>(); List<Integer> list =NewArraylist<>(); Getfactors (res, list, N,2); returnRes; }        Private voidGetfactors (list<list<integer>> res, list<integer> List,intNintfactor) {        if(N <= 1) {            if(List.size () > 1) Res.add (NewArraylist<integer>(list)); return; }                 for(inti = factor; I <= N; i++) {            if(n% i = = 0) {list.add (i); Getfactors (res, list, n/I, i); List.remove (List.size ()-1); }        }    }}

Reference:

254. Factor Combinations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.