第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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值