码迷,mamicode.com
首页 > 其他好文 > 详细

编程求解,输入两个整数n和m,从数列1,2,3,……n中随意取几个数,使其和等于m。要求将所有的可能组合列出来

时间:2017-09-19 22:55:24      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:linked   exti   asn   public   int()   return   print   else   system   

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    private static LinkedList<Integer> list = new LinkedList<>();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int n = scanner.nextInt();
            int m = scanner.nextInt();
            findSum(m, 1, n);
        }
    }

    public static void findSum(int sum, int start, int end) {
        if (sum < 0 || start > end + 1)
            return;
        else if (sum == 0){
            list.forEach(x ->System.out.print(x + " "));
            System.out.println();
            return;
        }
        if (sum >= start) {
            list.push(start);
            findSum(sum - start, start + 1, end);
            list.pop();
            findSum(sum, start+1, end);
        }
    }
}

 

编程求解,输入两个整数n和m,从数列1,2,3,……n中随意取几个数,使其和等于m。要求将所有的可能组合列出来

标签:linked   exti   asn   public   int()   return   print   else   system   

原文地址:http://www.cnblogs.com/huangyichun/p/7554041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!