Enter two integers, N and m, from the numbers 1, 2, 3 ,...... Random Number in N to make it equal to m

Source: Internet
Author: User

Question: programming, input two integers n and m, from the series 1, 2, 3 ,...... N is random, so that the sum is equal to M. All possible combinations are required.

Analysis: the idea of sub-governance. You can split the problem (m, n) into (m-N, N-1) and (m, n-1 ).

Note: When the value of 1 and N is greater than m, you can start searching from n = m.

2. End condition: n <1 | M <1

3. Print the output result. Note that printing the output result does not mean that the function call is complete. Taking n = 7 and M = 10 as an example, 7, 3, 7, 2, and 1 are all results, cannot be terminated at 7 or 3. The Print Output condition is n = m.

The program code is as follows:

Java

public class FindSum {    // used as a stack to save the result    private static LinkedList<Integer> list = new LinkedList<Integer>();    public static void findSum(int sum, int n) {        if (n < 1 || sum < 1)            return;        if (sum < n)            n = sum;        if (sum == n) {            for (int i = 0; i < list.size(); i++)                System.out.print(list.get(i) + " ");            System.out.print(sum);            System.out.println();        }        list.addLast(n);        findSum(sum - n, n - 1);        list.removeLast();        findSum(sum, n - 1);    }    public static void main(String[] args) {        int sum = 10;        int n = 8;        findSum(sum, n);    }}

 

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.