1. 程式人生 > >JAVA:遞迴實現輸出正整數和等於n的所有不增的正整數和式

JAVA:遞迴實現輸出正整數和等於n的所有不增的正整數和式

遞迴實現輸出正整數和等於n的所有不增的正整數和式(JAVA)

  • 碰到遞迴,瞬間感覺腦細胞不夠用了 其實感覺並沒有用到遞迴的精髓,更像是窮舉遍歷,把後面的判斷條件放到外面main函式 就完全是窮舉了
  • 關於陣列的使用,是受到書本上的提示
package pers.mine.test;

public class ToDo {
    int []a=new int[20];
    int oneNum=0;
    public static void main(String[] args) {
        ToDo one=new ToDo();
        one.oneNum=7
; one.a[0]=one.oneNum; System.out.print(one.oneNum+"="); System.out.printf("%2d\n",one.oneNum); one.exOne(one.oneNum, 0); } public void exOne(int num,int end){//表示最後一個位置是end,要分解的數為num //分解 a[end]=a[end]-1; int orther=num-a[end];//剩餘值 if
(orther<=a[end]){ a[end+1]=orther;//放入 end++;//使end與當前指向匹配 }else{ do{ a[end+1]=a[end]; end++; orther=orther-a[end]; }while(orther>a[end]); a[end+1]=orther;//放入 end++; } //後續沒清除的值會影響計算結果
int len=a.length; while((end+1)<=(len-1)&&a[end+1]!=0){ a[end+1]=0; end++;//end與指向匹配 } //輸出陣列 int i=0; System.out.print(this.oneNum+"="); while(a[i]!=0){ if(i==0){ System.out.printf("%2d",a[i]); }else{ System.out.printf("+%2d",a[i]); } i++; } System.out.println(); //判斷數組裡的值有沒有大於1的,有的話,繼續分解 int one=end; int temp=0; while(one>=0){ temp=temp+a[one]; if(a[one]>1){ this.exOne(temp, one); one=end; } one--; } //如果都沒有,說明分解完畢, } }

執行結果
這裡寫圖片描述