整數劃分/切割(Integer Partion),並輸出結果, java, python__python

來源:互聯網
上載者:User

整數劃分是一個比較典型的遞迴問題:將一個整數 n n n 劃分為值不超過 m m m 的一系列數的組合。
例如,若 n=5 n = 5 n=5, m=4 m = 4 m=4, 則劃分可以為:{4,1}, {3,1,1}, {3,2}, {2,1,1,1}, {2, 2, 1},{1,1,1,1,1}。共有 6 個組合。

若只要輸出劃分的總數,網上參考資料比較多,也比價容易理解。
若還要求把具體的劃分結果輸出,網上資料比較少,我自己從國外網站搜了下,找到了一個答案,同樣利用到了遞推思想,主要是:
函數中多了一個字串參數,並且當 n n n 值下降到 0 時,換行

java 代碼:

/** * @author chen zhen * @version 建立時間:2018年4月25日 下午4:51:23 * @value 類說明: 整數劃分,並輸出結果*/public class IntegerPartion {    // 查詢劃分次數    static int countPartion(int n, int m) {        if (n ==1 || m == 1)            return 1;        else if (m > n)            return countPartion(n, n);        else if (m ==n )            return 1 + countPartion(n, n-1);        else if (m < n)            return countPartion(n-m, m) + countPartion(n, m-1);        return 0;    }    // 輸出具體劃分    static void countOutput(int n, int m, String str) {        if (n == 0) // 遞迴跳出條件1            System.out.println(str);        else {            if (m > 1) // 遞迴跳出條件2                countOutput(n, m-1, str);            if (m <= n) // 因為遞迴時可能出現 m>n 的情況                countOutput(n-m, m, m + " " + str);        }    }    public static void main(String[] args) {        int m = 5;        int n = 6;        System.out.println(countPartion(m, n));        countOutput(m, n, "");    }}

Python 代碼:

# 輸出整數劃分個數def f1(n, m):    if n==0 or m ==0:        return 0    if n==1 or m ==1 :        return 1    if m == n:                return 1 + f1(n, n-1)    elif m > n:        return f1(n, n)    elif m < n:        return f1(n-m, m) + f1(n, m-1)# 輸出具體的整數劃分def f2(n, m, string):    if n == 0:        print(string)    else:        if m>1:            f2(n, m-1, string)        if m <= n:            f2(n-m, m, str(m)+ ' '+string) n = 5; m = 4print(f1(n, m))f2(n, m, '')

輸出結果:
6
1 1 1 1 1
1 1 1 2
1 2 2
1 1 3
2 3
1 4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.