用java编写程序:求正整数n所有可能的和式的组合。(例如给定正整数3,所有和加起来等于3的和式如下:3 =

求正整数n所有可能的和式的组合。(例如给定正整数3,所有和加起来等于3的和式如下:3 = 3 + 0 3 = 2 + 1 3 = 1 + 1 + 1 其中各个和式中的因子只能为自然数,因子允许重复出现。),这一题如果要求用递归的方式解,如何求解?

public class Test {
public static String res="";
public static void main(String[] args) {
int n=6;
System.out.println("0+"+n);//特殊 单独输出
res="1"; //初始化 通过找规律 这步必要
start(n);
}

private static void start(int n)
{
if(n>1)
{
System.out.println(res+"+"+(n-1)); //自己研究吧 很简单
res+="+1";
start(n-1);
}
}
}

0+6
1+5
1+1+4
1+1+1+3
1+1+1+1+2
1+1+1+1+1+1
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-04-14
import java.util.Scanner;

public class test {
public static void main(String[] args) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int m = 0;
while(n > 0) {
m *= 10;
m += n%10;
n /= 10;
}
System.out.println(m);
}
}本回答被提问者和网友采纳
第2个回答  2011-04-14
import java.util.Scanner;

public class test {
public static void main(String[] args) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int m = 0;
while(n > 0) {
m *= 10;
m += n%10;
n /= 10;
}
System.out.println(m);
}
}本回答被提问者和网友采纳
相似回答
大家正在搜