Easy Java solution with little change of Combination sum


  • 0
    U
    public class Solution {// I think the name of this problem can be combiantion product....
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(n==1) return result;
        getResult(result, new ArrayList<Integer>(),n, n, 2);
        return result;
    }
    
    private void getResult(List<List<Integer>> result, List<Integer> cur, int n, int target, int start){
        if(target == 1 ){
            result.add(new ArrayList<Integer>(cur));
            return;
        } 
        else if(target>0){
            for(int i = start; i<n&&i<=target; i++){
                if(target%i==0){
                    cur.add(i);
                    getResult(result, cur, n , target/i, i);
                    cur.remove(cur.size() - 1);
                }
            }
        }
        
    }
    

    }

    My Combination Sum code

    public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        helper(result, new ArrayList<Integer>(), candidates, target, 0);
        return result;
    }
    
    private void helper(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
        if(target == 0 ){
            result.add(new ArrayList<Integer>(cur));
            return;
        } 
        else if(target>0){
            for(int i = start; i < candidates.length && candidates[i]<=target; i++){
                cur.add(candidates[i]);
                helper(result, cur, candidates, target - candidates[i], i);
                cur.remove(cur.size() - 1);
            }
        }
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.