Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to find all possible combinations of numbers from an array that equal to N in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;

public class MyClass {
    static void GetCombinationsEqualToN(ArrayList<Integer> arr, int N, ArrayList<Integer> combination) {
       int sum = 0;
       
       for (int num: combination) sum += num;
       
       if (sum == N)
            System.out.println("sum(" + Arrays.toString(combination.toArray()) + ") = " + N);
       
       if (sum >= N)
            return;
            
       for (int i = 0; i < arr.size(); i++) {
             ArrayList<Integer> remaining = new ArrayList<Integer>();
             
             for (int j = i + 1; j < arr.size(); j++) remaining.add(arr.get(j));
             
             ArrayList<Integer> combination_next = new ArrayList<Integer>(combination);
             combination_next.add(arr.get(i));
             
             GetCombinationsEqualToN(remaining, N, combination_next);
       }
    }

    public static void main(String args[]) {
        Integer[] arr = {4, 6, 8, 2, 1, 10, 3, 5, 13};
        int N = 13;

        GetCombinationsEqualToN(new ArrayList<Integer>(Arrays.asList(arr)), N, new ArrayList<Integer>());
    }
}




/*
run:

sum([4, 6, 2, 1]) = 13
sum([4, 6, 3]) = 13
sum([4, 8, 1]) = 13
sum([4, 1, 3, 5]) = 13
sum([6, 2, 5]) = 13
sum([8, 2, 3]) = 13
sum([8, 5]) = 13
sum([2, 1, 10]) = 13
sum([10, 3]) = 13
sum([13]) = 13

*/

 



answered Oct 15, 2022 by avibootz
...