• 2017校招真题 求和-回溯法


    题目描述

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

    输入描述:

    每个测试输入包含2个整数,n和m

    输出描述:

    按每个组合的字典序排列输出,每行输出一种组合
    示例1

    输入

    5 5

    输出

    1 4
    2 3
    5

    1. import java.util.ArrayList;  
    2. import java.util.Scanner;  
    3.   
    4. /** 
    5.  * 题目描述 输入两个整数 n 和 m,从数列1,2,3.......n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来 输入描述: 
    6.  * 每个测试输入包含2个整数,n和m 输出描述: 按每个组合的字典序排列输出,每行输出一种组合 示例1 输入 
    7.  *  
    8.  * 5 5 输出 
    9.  *  
    10.  * 1 4 2 3 5 
    11.  *  
    12.  * @author Administrator 
    13.  * 
    14.  */  
    15.   
    16. public class Main {  
    17.     public static ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();  
    18.     public static ArrayList<Integer> currentList;  
    19.   
    20.     public static void main(String[] args) {  
    21.         Scanner scanner = new Scanner(System.in);  
    22.         while (scanner.hasNext()) {  
    23.             int n = scanner.nextInt();  
    24.             int m = scanner.nextInt();  
    25.             arrayList.clear();  
    26.             currentList = new ArrayList<>();  
    27.             func(1, n, m);  
    28.             for (ArrayList<Integer> l : arrayList) {  
    29.                 int i = 0;  
    30.                 for (; i < l.size() - 1; i++) {  
    31.                     System.out.print(l.get(i) + " ");  
    32.                 }  
    33.                 System.out.println(l.get(i));  
    34.             }  
    35.         }  
    36.     }  
    37.   
    38.     private static void func(int low, int n, int m) {  
    39.         if (m == 0) {  
    40.             arrayList.add(new ArrayList<>(currentList));  
    41.         }  
    42.         for (int i = low; i <= n && i <= m; i++) {  
    43.   
    44.             currentList.add(i);  
    45.             func(i + 1, n, m - i);  
    46.             currentList.remove(currentList.size() - 1);  
    47.         }  
    48.   
    49.     }  
    50.   
    51. }  
  • 相关阅读:
    centos 创建swap 交换分区
    nginx android app 慢网络请求超时
    使用docker toolbox 在windows上搭建统一环境
    Docker Volume 之权限管理(转)
    一次架构失误的反思
    Cannot connect to the Docker daemon. Is the docker daemon running on this host?
    docker-compose启动报错,解决方案
    php 执行程序分析
    继电器是如何成为CPU的(2)
    [每天默写一个算法]KMP
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7387819.html
Copyright © 2020-2023  润新知