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); }}