求java高手帮忙!!!

问题是这样的,写个程序,要求如下
x_1 + x_2 + x_3 + ... + x_k = n
可自己输入n和k是什么数字,
举个例,
如果k为3,n为4
那么要出来这个样子
x_1 x_2 x_3
4 0 0
3 1 0
3 0 1
2 2 0
2 1 1
2 0 2
1 3 0
1 2 1
1 1 2
1 0 3
0 4 0
0 3 1
0 2 2
0 1 3
0 0 4
要整个程序,做的好追加
最新回答
枕边徒留芳香

2025-06-17 01:07:45

import java.util.*;

public class Ex3_3 {

public static void main(String[] args) {
int n, k;
int[] arr;
Scanner scan = new Scanner(System.in);
do{
System.out.print("input n : ");
n = scan.nextInt();
}while(n <= 0); //insure n is positive integer

do{
System.out.print("input k : ");
k = scan.nextInt();
}while(k <= 0); //insure k is positive integer

arr = new int[k+1];
arr[0] = k;

func(n, k, arr);
}

public static void func(int n, int k, int[] arr){
int i, j;
for(i=n; i>=0; i--){
arr[k] = i;
if(k > 1){
func(n-i, k-1, arr);
}
else{
if(n-i == 0){
for(j=arr[0]; j>=1; j--){
System.out.print(arr[j] + "\t");
}
System.out.println();
}
}
}
}
}

输出测试:
input n : 6
input k : 4
6 0 0 0
5 1 0 0
5 0 1 0
5 0 0 1
4 2 0 0
4 1 1 0
4 1 0 1
4 0 2 0
4 0 1 1
4 0 0 2
3 3 0 0
3 2 1 0
3 2 0 1
3 1 2 0
3 1 1 1
3 1 0 2
3 0 3 0
3 0 2 1
3 0 1 2
3 0 0 3
2 4 0 0
2 3 1 0
2 3 0 1
2 2 2 0
2 2 1 1
2 2 0 2
2 1 3 0
2 1 2 1
2 1 1 2
2 1 0 3
2 0 4 0
2 0 3 1
2 0 2 2
2 0 1 3
2 0 0 4
1 5 0 0
1 4 1 0
1 4 0 1
1 3 2 0
1 3 1 1
1 3 0 2
1 2 3 0
1 2 2 1
1 2 1 2
1 2 0 3
1 1 4 0
1 1 3 1
1 1 2 2
1 1 1 3
1 1 0 4
1 0 5 0
1 0 4 1
1 0 3 2
1 0 2 3
1 0 1 4
1 0 0 5
0 6 0 0
0 5 1 0
0 5 0 1
0 4 2 0
0 4 1 1
0 4 0 2
0 3 3 0
0 3 2 1
0 3 1 2
0 3 0 3
0 2 4 0
0 2 3 1
0 2 2 2
0 2 1 3
0 2 0 4
0 1 5 0
0 1 4 1
0 1 3 2
0 1 2 3
0 1 1 4
0 1 0 5
0 0 6 0
0 0 5 1
0 0 4 2
0 0 3 3
0 0 2 4
0 0 1 5
0 0 0 6
白发悲花落

2025-06-17 00:27:14

public class Test {

public static void main(String args[])
{
int n=4;
int k=3;

calculate( n, k);
}

private static void calculate(int n,int k) {
for(int i=1;i<k+1;i++)
System.out.print("x_"+i+" ");
System.out.println(" ");

for(int i=0;i<n+1;i++)
for(int j=0;j<n+1;j++)
for(int m=0;m<n+1;m++)
{
if((i+j+m)==n)
System.out.println(i+" "+j+" "+m);
}

}

}
大概就是这样啦,具体打印时候格式之类自己在修改看看~~
还有,x1我是从低到高打印的,换成你那种的话for(int i=n+1;i>0;i--)
自己动手写写吧~~
追问
对是对的,但是有两点,一,你这个只能是k为3的时候,我要通用,不管k是几,
二,怎么样让那底下的数字和x1,x2,x3对齐啊???现在出来就是不对齐的
紫萌雨

2025-06-17 02:38:19

一楼的,如果K增大了就不能得到想要的效果了
冷冰雨

2025-06-17 00:29:22

这哪是java提啊,这是算法题