LeetCode – Factor Combinations (Java)

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:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.

Java Solution

public List<List<Integer>> getFactors(int n) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();
    helper(2, 1, n, result, list);
    return result;
}
 
public void helper(int start, int product, int n, List<List<Integer>> result, List<Integer> curr){
    if(start>n || product > n )
        return ;
 
    if(product==n) {
        ArrayList<Integer> t = new ArrayList<Integer>(curr);
        result.add(t);
        return;
    }   
 
    for(int i=start; i<n; i++){
        if(i*product>n)
            break;
 
        if(n%i==0){
            curr.add(i);
            helper(i, i*product, n, result, curr);
            curr.remove(curr.size()-1);
        }
    }
}

18 thoughts on “LeetCode – Factor Combinations (Java)”

  1. Great explanation of the Factor Combinations problem on LeetCode! The step-by-step breakdown makes it much easier to grasp the logic behind finding all possible combinations. It’s a challenging problem, but your approach helps clarify how to solve it effectively. This is definitely useful for anyone preparing for technical interviews or looking to improve their problem-solving skills.

    On a side note, if you’re a content creator, you might want to check out Asteroid Production’s YouTube studio. Whether you’re filming tutorials, coding videos, or vlogs, their fully-equipped YouTube studio provides everything needed for high-quality production. For anyone looking to enhance their video content, a professional YouTube studio like Asteroid Production’s can make a huge difference in production quality.

  2. Fantastic article. This item offers an exceptional Java solution to the factor combinations on LeetCode problem. We appreciate ProgramCreek sharing this useful and well-written code. Anyone wishing to improve their problem-solving abilities should definitely use it. Continue your amazing work.
    Best SEO Services In Hyderabad
    https://betopseo.com/

Leave a Comment