第21题:求1~n序列中等于m的所有组合

欢迎转载,转载请务必注明出处: 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。 *要求将其中所有的可能组合列出来。 */{(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);}(int num, int n, int m, Integer[] combination){//num大于m,或者num超过了nif (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);}(String[] args){getAllCombinations(7,8);}} <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 Process finished with exit code 0

的这一半更多地赢取上帝掌握的那一半。

第21题:求1~n序列中等于m的所有组合

相关文章:

你感兴趣的文章:

标签云: