3

Given an array of integers and a sum, the task is to print all subsets of given array with sum equal to given sum with repetitions allowed.

Examples :

Input : arr = {1, 5, 6}, N = 7

Output :
1 1 1 1 1 1 1
1 1 5
1 5 1
5 1 1
1 6
6 1

I have already gone through related DP questions from https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/ , https://www.geeksforgeeks.org/ways-sum-n-using-array-elements-repetition-allowed/ and find all subsets that sum to a particular value

I haven't found a way or any clues on how to solve this question with repetitions allowed. Any leads would be helpful.

arkham knight
  • 373
  • 7
  • 18

3 Answers3

4

Something like this?

function f(A, N, r=[], s=N){
  if (s == 0)
    return [r];

  result = [];

  for (let a of A)
    if (a <= s)
      result = result.concat(
        f(A, N, r.slice().concat(a), s-a));

  return result;
}

console.log(JSON.stringify(f([1,5,6], 7)));
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61
1

Here is a simple solution in Java:

public class PrintAllSubsets {

    public static void main(String[] args) {
        int arr []= {1, 5, 6}; 
        int N = 7;
        allSubsets(arr,N,"");
    }

    private static void allSubsets(int[] arr, int n, String res) {

        if(n == 0) {
            System.out.println(res);
            return;
        }
        for(int i = 0; i<arr.length;i++) {
            if(n >= arr[i]) {
                allSubsets(arr, n-arr[i], res + arr[i]);
            }
        }
    }

}
mjuarez
  • 16,372
  • 11
  • 56
  • 73
S TEJESH
  • 11
  • 1
0

Sort the input array (if you can) and then use https://en.wikipedia.org/wiki/Backtracking to get all possible solutions. Just go from the lowests number and if it cannot fit, just start returning and check if number one-item higher (in input array) can fit instead.

libik
  • 22,239
  • 9
  • 44
  • 87