Monday, 27 November 2017

Given a number N, write a java program that returns all possible combinations of numbers that add up to N, as lists. //(Exclude the N+0=N)


Code:

//For example, if N=4 return {{1,1,1,1},{1,1,2},{1,3}}

//if N = 6 ... expected results
//1,1,1,1,1,1
//2,1,1,1,1
//2,2,1,1
//2,2,2
//3,1,1,1
//3,2,1
//3,3
//4,1,1
//4,2
//5,1


import java.util.*;

class Solution {

    public static void addNext(ArrayList> results, ArrayList list, int sum, int last, int target, boolean isFirst) {
        if (sum == target) {
        results.add(list);
        return;
        }
            
            
        while (sum + last > target) {
            last--;
        }

        int less = last - 1;
        if ( !isFirst && less > 0 && less + last < target ) {
        ArrayList copyList = new ArrayList(list);
        addNext(results, copyList, sum, less, target, false);
        }
        
        sum = sum + last;
        list.add(last);
        
        addNext(results, list, sum, last, target, false);
    }

    public static void main(String[] args) {
        int n = 6;
        ArrayList> results = new ArrayList>();
        
        ArrayList list;
        
        for (int i=1; i
            list = new ArrayList();
            addNext(results, list, 0, i, n, true);
        }

        print(results);
         
    }
    
    public static void print(ArrayList> results) {
    for (ArrayList list: results) {
    for (Integer i: list) {
    System.out.print(String.format("%d ", i));
    }
    System.out.println("\n----------");
    }
    }
    
}



Output:

Execute and get the output


More Java Programs:
















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...