all the content comes from the programming method: Interview and algorithm experience book, the implementation is written by themselves using JavaTitle Description
Enter two integers n and sum to arbitrarily take a few numbers from the sequence 1,2,3.......N, making them equal to sum, requiring all possible combinations of them to be listed.
Analysis and Solution method one
Note that take n, and do not take n differences can be, consider whether to take the nth number of strategies, can be converted to a only and the number of previous n-1 of the problem.
- If the number of nth, then the problem is converted to "take the number of n-1 to make their and sum-n", the corresponding code statement is Sumofknumber (Sum-n, n-1);
- If the number of nth is not taken, then the problem is converted to "sum of the preceding n-1 so that they are sums", and the corresponding code statement is Sumofknumber (sum, n-1).
The reference code is as follows:
/** Find and set multiple number of values*/ Public classSearchsomesurevalue {Static intlength; Static voidFindresult (intNintMintflag[]) { if(n<=0| | M<=0) { return; } if(n>m) {n=m; } if(n==m) {flag[n-1]=1; for(inti = 0; i < length; i++) { if(flag[i]==1) {System.out.print (i+1+ ""); }} System.out.println (); Flag[n-1]=0; } flag[n-1]=1; Findresult (n-1, M-n, flag); Flag[n-1]=0; Findresult (n-1, M, flag); } Public Static voidMain (string[] args) {intN=5,m=5; Length=N; int[] flag=New int[n]; Findresult (n, m, flag); }}
Programming approach: Interviewing and algorithmic insights (finding and determining multiple numbers of values)