求一道java程序设计题(整数划分)

整数的分划问题。
如,对于正整数n=6,可以分划为:
6
5+1
4+2, 4+1+1
3+3, 3+2+1, 3+1+1+1
2+2+2, 2+2+1+1, 2+1+1+1+1
1+1+1+1+1+1+1
现在的问题是,对于给定的正整数n,编写算法打印所有划分。
用户从键盘输入 n (范围1~10)
程序输出该整数的所有划分。
没有代码的话告诉我思路也行!

public static void main(String[] args) {

   Scanner sca = new Scanner(System.in);

   int n = sca.nextInt();

   int m = n;

   int m2 = 0;

   String str = "";

   if(n == 1) {

    System.out.println(1);

   }

   go_to:

   while(n > 1) {

    n--;

    if(n == 1&&m2 != 0) {

     str = str+"+1";

     System.out.println(n+"+"+m2+str);

     break go_to;

    }

    if(n == 1) {

     str = str+"+1";

     System.out.println(n+str);

     break go_to;

    }

    str = "";

    m2 = m - n;

    System.out.print(n+"+"+m2+" ");

    if(m2 == 1) {

     System.out.println();

    }

    else {

     do{

      m2--;

      str = str + "+1";

      System.out.print(n+"+"+m2+str+" ");

     }while(m2 > 1);

     System.out.println();

    }

   }

  }

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-05-03
这个可以用递归来实现。。。。。代码如下。。。还是想了很久弄出来的。。。。已经测试了的。。。希望能帮到你。。。

import java.util.Scanner;

public class Test {

public static void huafenD(int oldData,int j, int n,StringBuffer result){
StringBuffer r = new StringBuffer(result);
for( int i = j;i<=n;i++){
if(i==n&&i!=oldData) {
result.append(i);
System.out.println(result.toString());
result = new StringBuffer(r);
}
else if(i!=oldData){
result.append(i);
result.append("+");
huafenD(oldData,i,n-i,result);
result = new StringBuffer(r);

}

}

}

public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("请输入一个整数(1-10)");
int data = in.nextInt();
while(data<1||data>10){
System.out.println("您的输入 不符合要求,请重新输入");
data = in.nextInt();
}

if(data==1)System.out.println("无需划分");
else {
StringBuffer sb = new StringBuffer();
huafenD(data,1,data,sb);
}
}
}
运行结果示例:
请输入一个整数(1-10)
6
1+1+1+1+1+1
1+1+1+1+2
1+1+1+3
1+1+2+2
1+1+4
1+2+3
1+5
2+2+2
2+4
3+3本回答被提问者采纳
第2个回答  2011-05-03
首先肯定是1+1+1这种类型的 然后是1+2+。。。这种类型 然后是1+2+3这种
也就是给定一个数字 你要判断在1+2+3+。。n的范围里 然后再分不同条件
第3个回答  2011-05-05
找老师吧,这种题没人有耐性给你做的,好好学习,自己搞定,祝你成功
另外,虚机团上产品团购,超级便宜
第4个回答  2011-05-04
找老师吧,这种题没人有耐性给你做的,好好学习,自己搞定,祝你成功
相似回答