Programming approach: Interviewing and algorithmic insights (finding and determining multiple numbers of values)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.