[Microsoft Google interview 100 question-[21] finding all the combinations for m from 1-n

Source: Internet
Author: User

Question 21st:

Enter two integers, N and m, from the series 1, 2, 3 ....... N returns a few random numbers to make it equal to M. All possible combinations must be listed.

When I saw such a question, I had no idea where to start. By collecting information online, I finally got it done.

Let's take a look at the following ideas:

Given N and m;

1. Determine N * (n + 1)/2And MRelationship

IfN * (n + 1)/2> mIf there is a drama, we can continue,

IfN * (n + 1)/2 <m
No, because1, 2,... nThe sum of all numbers is notMBig. Therefore, log out directly.

2. Then find the number in a loop.

The starting condition of the loop must be fromI = 1Start, but where does it end?
The condition for loop is:I <n & I <m/2Is the focus,I <nYes. The key is later.I <m/2Because ifI
> = M/2
IA large numberIThe sum must be greaterM.

3. Recursive Solution


Code:

Public class algorithm21_0 {static void getallcomp (int n, int m) {string pre = m + "="; int themax = (1 + n) * n/2; if (themax <m) {system. out. println ("this number does not exist! ");} Else {for (INT I = 1; I <n & I <= m/2; I ++) {// count from 1, print the combination of two numbers, and the two numbers are not equal if (I! = M-I & (M-I) <= N) {system. out. println ("here:" + pre + I + "+" + (m-I); // continue;} // call recursion, continue to obtain the combination of more than 2 numbers gettheresult (m-I, pre + I, I, n) ;}// call recursion and continue to obtain the combination of more than 2 numbers, J is the number used in the combination, so the number is greater than this number. Static void gettheresult (int m, string pre, Int J, int N) {for (INT I = J + 1; I <n & I <= m/2; I ++) {if (I! = M-I & (M-I) <= n) system. out. println ("Fuck:" + pre + "+" + I + "+" + (m-I); gettheresult (m-I, pre + "+" + I, i, n) ;}} public static void main (string [] ARGs) {getallcomp (10, 11 );}}

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.