考虑“ n之和的问题:”给定一个正整数n,列出所有不同的方法来获得合计ton的正整数集合。假设我们不在乎顺序,那么1 + 2和2 +1是相同的可能性。对于n = 3,可能性是1 +1 + 1、1 + 2、3
import java.util.Scanner;
public class SumsToN {
static void listNumber(int arr[], int n, int i)
{
int MAX_POINT = 3;
if (n == 0)
{
printArray(arr, i);
}
else if(n > 0)
{
for (int k = 1; k <= MAX_POINT; k++)
{
arr[i]= k;
listNumber(arr, n-k, i+1);
}
}
}
static void printArray(int arr[], int m)
{
for (int i = 0; i < m; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main (String[] args)
{
System.out.print("enter n number: " );
Scanner input = new Scanner(System. in);
int n = input.nextInt();
int size = 100;
int[] arr = new int[size];
System.out.println("list of all the possibilities of "+ n + " are");
listNumber(arr, n, 0);
}
}
我的工作有些不正确,因为当我输入n = 5时,它不包括例如1 4 而且它的顺序是错误的,例如1 + 1 + 2,而不是1 + 2 + 1 ---即,“顺序无关紧要
有人可以帮我吗?
$ java SumsToN
enter n number: 5
list of all the possibilities of 5 are
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2
$ java SumsToN
enter n number: 3
list of all the possibilities of 3 are
1 1 1
1 2
2 1
3