輸入兩個整數n和m,從數列1,2,3,……n中隨意取幾個數,使其和等於m

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   color   

題目:編程求解,輸入兩個整數n和m,從數列1,2,3,……n中隨意取幾個數,使其和等於m。要求將所有的可能組合列出來。

分析:分治的思想。可以把問題(m,n)拆分(m - n, n -1)和(m, n - 1)。

注意點:1、n大於m時,可直接從n = m出開始搜尋

    2、結束條件:n < 1 || m < 1

    3、列印輸出結果。注意列印輸出結果並不代表函數調用結束,以n = 7 和 m = 10為例,7、3和7、2、1都是一種結果,不能得到7、3的時候終止。列印輸出的條件是n = m

程式碼如下:

Java

public class FindSum {    // used as a stack to save the result    private static LinkedList<Integer> list = new LinkedList<Integer>();    public static void findSum(int sum, int n) {        if (n < 1 || sum < 1)            return;        if (sum < n)            n = sum;        if (sum == n) {            for (int i = 0; i < list.size(); i++)                System.out.print(list.get(i) + " ");            System.out.print(sum);            System.out.println();        }        list.addLast(n);        findSum(sum - n, n - 1);        list.removeLast();        findSum(sum, n - 1);    }    public static void main(String[] args) {        int sum = 10;        int n = 8;        findSum(sum, n);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.