Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3051
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  孤街浪徒
    2020-11-21 07:08

    This can be used to print all the answers as well

    public void recur(int[] a, int n, int sum, int[] ans, int ind) {
        if (n < 0 && sum != 0)
            return;
        if (n < 0 && sum == 0) {
            print(ans, ind);
            return;
        }
        if (sum >= a[n]) {
            ans[ind] = a[n];
            recur(a, n - 1, sum - a[n], ans, ind + 1);
        }
        recur(a, n - 1, sum, ans, ind);
    }
    
    public void print(int[] a, int n) {
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }
    

    Time Complexity is exponential. Order of 2^n

提交回复
热议问题