Enter two integer values N and m to find all combinations of integers 1 to n and M

Source: Internet
Author: User
Tags printf

Enter two integer values N and m to find all combinations of integers 1 to n and M
Cases:
Input: n=10 m=10
Output:
1 2 3 4
1 2 7
1 3 6
1 4 5
1 9
2 3 5
2 8
3 7
4 6
10

Ideas:

1. The full arrangement of the output 1-n
2. Restrictions: The first I item is equal to M, then outputs the first I, otherwise does not output
3. After searching for the value J, no further search is no longer included J (after searching for the element containing 1, subsequent searches no longer search for element 1 After searching for elements containing the value 2 no longer searching for element 2)

The code is as follows:

 #include <stdio.h> #include <iostream> using namespace std;//print result void Print_res (
    int *a,int N) {for (int i=1;i<n;i++) printf ("%d", a[i]);
printf ("\ n");
    }//Recursive search for void dfs (int *data,int *index,int step,int n,int m,int sum) {int i;
    if (Sum > M)//no longer looks for return;
        else if (sum = = m)//output {print_res (data,step);
    Return
            } for (i=data[step-1]+1;i<=n;i++)//Key {if (index[i]==0)//The element has not been used {data[step]=i;
            Index[i]=1;
            DFS (Data,index,step+1,n,m,sum+i);
        index[i]=0;
}} return;
    } int main () {int m,n;
    cin>>n>>m;
    int *index=new int[n+1];
    int *data=new int[n+1];
        for (int i=0;i<n+1;i++) {index[i]=0;
    data[i]=0;
    } dfs (data,index,1,n,m,0);
    Delete [] index;
    delete [] data;
return 0; }

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.