从 N 个数中,取 M 个数的组合(枚举),要求不重复

package com.test;

/**
 * @ClassName TestLk
 * @Description 从 N 个数中,取 M 个数的组合(枚举),要求不重复;比如:彩票 36 选 7
 *         2、3、7、11、20、22、31
 *         3、2、7、11、20、22、31
 *         视为相同的一组
 * @Author lk
 * @Date 2022/2/16 12:19
 * @Version 1.0
 **/
public class TestLk {
    
    
        static int N = 6;
        static int M = 3;
        static int[] a = new int[]{
    
    1, 2, 3, 4, 5, 6};
        static int[] b = new int[M];

        public static void main(String[] args){
    
    
            C(N,M);
        }

        // 递归法
        static void C(int m,int n){
    
    
            int i,j;
            for(i=n;i<=m;i++) {
    
    
                b[n-1] = i-1;  // 计算a数组的下标
                if(n>1)
                    C(i-1,n-1);  // 当b数组的下标大于1,进行递归,否则:输出一组值
                else {
    
    
                    // for(int a:b)
                    //     System.out.println(a);
                    for(j=0;j<=M-1;j++)
                        if(j == (M-1)){
    
    
                            System.out.print(a[b[j]]);
                        }else{
    
    
                            System.out.print(a[b[j]] + "、");
                        }
                    System.out.println();
                }
            }
        }
}

输出结果:
123
124
134
234
125
135
235
145
245
345
126
136
236
146
246
346
156
256
356
456

猜你喜欢

转载自blog.csdn.net/weixin_43317914/article/details/122969172