zoukankan      html  css  js  c++  java
  • 第21题:求1~n序列中等于m的所有组合

    欢迎转载,转载请务必注明出处:http://blog.csdn.net/alading2009/article/details/46582559
    github:https://github.com/frank-cq/MyTest

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


    代码

    package test021;
    
    import common.CommonFunctions;
    
    /**
     * Created by cq on 2015/5/15.
     * 第21题:输入两个整数n和m,从数列 1,2,3,...,n中随意取几个数,使其和等于m。
     *        要求将其中所有的可能组合列出来。
     */
    public class Test021 {
        public static void getAllCombinations(int n, int m){
            //据等差数列求和公式,计算m超过n的表达上限
            if (n <= 0 || m <= 0 || m > n*(1+n)>>1){
                System.out.println("输入参数非法或m超出1...n序列的表示范围!");
                return;
            }
    
            Integer[] combination = new Integer[n];
    
            recursionProcedure(1,n,m,combination);
        }
        //递归求解,combination的每一个位置对应1~n中的一个数,在组合过程中一个数有两种情况,要么被选中,要么被放弃
        public static void recursionProcedure(int num, int n, int m, Integer[] combination){
            //num大于m,或者num超过了n
            if (num > m || num > n){
                return;
            }
            if (num == m){
                combination[num-1] = num;
                CommonFunctions.printPartArray(combination,num-1);
                return;
            }
    
            //num被选中
            combination[num-1] = num;
            recursionProcedure(num+1,n,m-num,combination);
    
            //num被放弃
            combination[num-1] = null;
            recursionProcedure(num+1,n,m,combination);
        }
        public static void main(String[] args){
            getAllCombinations(7,8);
        }
    }
        //打印数组
        public static <T> void printPartArray(T[] array, int maxIndex){
            for (int i=0; i<=maxIndex; i++){
                if (array[i] != null){
                    System.out.print(array[i]+" ");
                }
            }
            System.out.println();
        }
    



    执行结果

    Connected to the target VM, address: '127.0.0.1:8695', transport: 'socket'
    Disconnected from the target VM, address: '127.0.0.1:8695', transport: 'socket'
    1 2 5 
    1 3 4 
    1 7 
    2 6 
    3 5 
    
    Process finished with exit code 0
  • 相关阅读:
    继承映射
    一对多,多对一,自关联的配置
    Spring 配置自动扫描spring bean配置
    Dao 处理
    2019暑假集训 括号匹配
    2019暑假集训 BLO
    2019暑假集训 Intervals
    2019暑假集训 平板涂色
    2019暑假集训 走廊泼水节
    0002-五层小山
  • 原文地址:https://www.cnblogs.com/read-the-spring-and-autumn-annals-in-night/p/12041972.html
Copyright © 2011-2022 走看看