algorithm - Find all M-length sets of positive integers that sum to N -


the problem i'm trying solve how find integer sets [a1, a2, ... ,am] that

a1 + a2 + ... + = n 

and constraint ai >= 1

for example if m = 4, , n = 7 there 3 answers

[1,1,1,4] [1,1,2,3] [1,2,2,2] 

since have print sets sum n. can employ complete search algorithm using recursion. in following code, m number of numbers in set , n sum required.

        int m;         int n;          void run(){             m = 4;             n = 7;             int[] arr = new int[m];             print(arr, 0, n, 1);         }  // req holds required sum numbers in array arr[from]  // arr[m-1].  // "last" holds last value had put in array. // first call array last=1.          void print(int[] arr, int from, int req, int last){             // reached end of array , sum required 0.              if(from==m && req==0){                 system.out.println(arrays.tostring(arr));                 return;             }               // either reached end of array sum not equal n            // or if have not reached end of array sum has             // become more or equal n.              if(from==m || req<=0){                 return;             }                for(int i=last; i<=req; i++){                 arr[from] = i;                 print(arr, from+1, req-i, i);             }         } 

output m=4 , n=7:

[1, 1, 1, 4] [1, 1, 2, 3] [1, 2, 2, 2] 

output m=3 , n=10:

[1, 1, 8] [1, 2, 7] [1, 3, 6] [1, 4, 5] [2, 2, 6] [2, 3, 5] [2, 4, 4] [3, 3, 4] 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -