Java求出一個給定集合的全部子集

思路:html

        假設集合有4個元素{a,b,c,d},那麼作一個for循環從0到15,每次輸出一個子集。0(0000)表示空子集,1(0001)由於最低位爲1,因此在集合四個元素中取第一個元素{a}做爲一個子集,2(0010)由於次低位爲1,因此在集合四個元素中取第二個元素{b}做爲一個子集,3(0011)由於最低位和次低位都爲1,因此在集合四個元素中取第1、第二個元素{a,b}做爲一個子集......,依次類推15(1111)表示{a,b,c,d}。
再舉個詳細例子:
假設有集合{a,b,c},則:
迭代0到2^n-1==0到7
0(000):{}
1(001):{a}
2(010):{b}
3(011):{ab}
4(100):{c}
5(101):{a,c}
6(110):{b,c}
7(111):{a,b,c}
java


代碼:spa

package demo16;

import java.util.HashSet;
import java.util.Set;

public class SubSet {
	public static void main(String[] args) {
		int[] set = new int[] { 1, 2 ,3};
		Set<Set<Integer>> result = getSubSet(set); // 調用方法
		// 輸出結果
		for (Set<Integer> subSet : result) {
			for (Integer num : subSet)
				System.out.print(num);

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

	public static Set<Set<Integer>> getSubSet(int[] set) {
		Set<Set<Integer>> result = new HashSet<Set<Integer>>(); // 用來存放子集的集合,如{{},{1},{2},{1,2}}
		int length = set.length;
		int num = length == 0 ? 0 : 1 << (length); // 2的n次方,若集合set爲空,num爲0;若集合set有4個元素,那麼num爲16.

		// 從0到2^n-1([00...00]到[11...11])
		for (int i = 0; i < num; i++) {
			Set<Integer> subSet = new HashSet<Integer>();
			int index = i;
			for (int j = 0; j < length; j++) {
				if ((index & 1) == 1) { // 每次判斷index最低位是否爲1,爲1則把集合set的第j個元素放到子集中
					subSet.add(set[j]);
				}
				index >>= 1; // 右移一位
			}

			result.add(subSet); // 把子集存儲起來
		}
		return result;
	}

}

結果:code

1
2
12
3
13
23
123
相關文章
相關標籤/搜索