一个简单的子集产生算法

来源:互联网 发布:淘宝9.9疯抢领红包链接 编辑:程序博客网 时间:2024/05/22 08:01

 

 char[] A={'a','b','c','d',...},集合A中,产生所有A的子集{'a'},{'b'},{'a','b'},{'a','b','c'}...这些。

方法一: 根据二进制产生

import java.text.*;

public class SubSet {

    
public static void main(String[] args) {
        
char[] chs = {'a''b''c''d'};
        
int len = 4;
        
        
for (int i = 0; i < Math.pow(2,len); i++)
        
{
            String str 
= Integer.toBinaryString(i);
            
int toBinary = Integer.parseInt(str);
            DecimalFormat df 
= new DecimalFormat("0000");
            str 
= df.format(toBinary);
            
char[] toCharArray = str.toCharArray();
            System.out.print(
"{");
            
for (int j = 0; j < toCharArray.length; j++)
            
{
                
if (toCharArray[j] == '1')
                    System.out.print(chs[j] 
+ ",");
            }

            System.out.println(
"}");
        }

    }

}

 

方法二:

public class PossibleSet 
{    
    
public static void main(String[] args) 
    
{        
        
int[] set = new int[4];        
        
char[] chs = {'a''b''c''d'};
        
int i, n, position = 0;         
        set[position] 
= 1;         
        
while(true
        
{             
            System.out.print(
"{" + chs[set[0- 1]);  // 第一个数             
            for(i = 1; i <= position; i++)                 
                System.out.print(
"," + chs[set[i] - 1]);             
            System.out.println(
"}");             
            
if(set[position] < set.length) 
            
{  // 递增集合个数                 
                set[position+1= set[position] + 1;                 
                position
++;             
            }
             
            
else if(position != 0
            
{  // 如果不是第一个位置                 
                position--;       // 倒退                 
                set[position]++;  // 下一个集合尾数             
            }
             
            
else  // 已倒退至第一个位置                 
                break;         
        }
                 
        System.out.println();    
    }

}


 

原创粉丝点击