求n个数中,任意m个数的组合

 1 import java.util.Scanner;
 2 
 3 public class 求子集的组合问题2 
 4 {
 5     static void perm(int n,int k)
 6     {
 7         //int num=0;
 8         for(int i=0;i<(1<<n);i++)
 9         {
10             int kk=i;
11             int num=0;
12             while(kk>0)//kk一直在变
13             {
14                 kk=kk&(kk-1);//表达的意义是消除掉最末尾的1后,表达的权值
15                 num++;//统计该数中1的数量
16             }
17             if(num==k)//如果该数的1的为数为num,则输出其位数上的1
18             {
19                 for(int j=0;j<n;j++)
20                     if((i&(1<<j))!=0)
21                         System.out.print(j);
22                 System.out.println();
23             }
24         }
25     }
26     public static void main(String[] args) 
27     {
28         // TODO 自动生成的方法存根
29         Scanner sc=new Scanner(System.in);
30         int n=sc.nextInt();//表示n个数
31         int k=sc.nextInt();//表示m个数
32         perm(n,k);
33     }
34 
35 }

需要注意的点是,该代码解决的是n个数中任意m个数的组合。

kk&(kk-1),其表达的意思是去掉末尾的1,如:1011 & (1011-1)= 1011&1010 =1010 

1010&(1010-1)  = 1010&1001 =1000    

猜你喜欢

转载自www.cnblogs.com/ybc7/p/11480363.html