find a subset of strings

To find a subset of a string, for example, to find a substring of 1234, there are 1, 2, 3, 4, 12, 13, 14, 23, 24, 34, 123, 124, 134, 234, 1234.. At that time, there was no I figured out how to do it. When I entered the second side, the interviewer asked the question of the written test. Now I think I should do it. Unfortunately, I did not think carefully after the written test. I learned this lesson and referred to some ideas on the Internet. Using recursion is the easiest way to find all subsets of a string.

All elements in the set have two possibilities for each subset: in the subset or not. 
These two possibilities for individual elements combine to form all subsets of a set. Each set has 2^n subsets. The proper subset is: (2^n)-1

We put the element in the state of being in the subset or not in the boolean array.

/**
 * 求1234的子串,例如:1,2,3,4,12,13,14,23,24,34,123,124,134,234,1234
 * 
 * 集合中的所有元素对于每一个子集来说,都有两种可能性:在子集中或是不在子集中。
 * 各个元素的这两种可能性组合起来,组成了一个集合的所有子集。每一个集合都有2^n个子集。
 * 
 * 我们把元素这种在或不在子集中状态,放置在boolean数组中。
 * @author c
 *
 */
public class Test {


    private static void get_Subset(String str, int start, int end, boolean[] b) {
        // TODO Auto-generated method stub
        if(start==end){//当start==end时,即集合中的所有元素都已经在或者不在该子集中,输出该子集后,return跳出该层递归。 
            int i = 0;
            for(;i<end;i++){
                if(b[i]){
                    System.out.print(str.charAt(i));
                }
            }
            System.out.print(" ");
            return ;
        }else{
            b[start] = false;//代表数组中索引为start的元素不在该子集中
            get_Subset(str, start+1, end, b);//而后进入递归,元素索引向后加一,同样索引为start+1的元素也有在或者不在该子集中两种可能性
            b[start] = true;
            get_Subset(str, start+1, end, b);
        }
    }

    public static void main(String[] args) {
        String str = "1234";
        //我们把元素这种在或不在子集中状态,放置在boolean数组中。
        boolean []b = new boolean[str.length()];
        get_Subset(str,0,str.length(),b);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733497&siteId=291194637