java编写求集合的全体子集

若求解集合中的全部子集,只需从头开始遍历即可,比如:我们想求集合{A,B,C,D}的全部子集,我们发现它的全部子集可以从头开始遍历{, A, AB, ABC, ABCD, AC, ACD, AD, B, BC, BCD, BD, C, CD, D},当一个链结束后比如ABCD,取出第一个元素A再进行重新开始遍历形成AC。当发现规律后,我们便可以开始编写代码:

import java.util.ArrayList;

import java.util.List;

public class test6 {

        public static List recursionSet(String[] arr) {
        List list = new ArrayList();
        list.add("");
        int i,j,k,n;
        n = arr.length;
        for(i = 0;i < n;i++){
              String s;
              s = arr[i];
              list.add(s);
              for(k = 1;k < n-i;k++){
                    for(j = i+k;j < n;j++){
                         s += arr[j];
                         list.add(s);
                         if(j == n-1){
                              s = s.substring(0, 1);
                         }
                    }
             }
       }
       return list;
      }

      public static void main(String[] args) {
               String s = "A B C D";
               String[] arr = s.split("\t");
               System.out.println(recursionSet(arr));

      }


}

你可能感兴趣的:(面试算法)