利用java怎么對集合的子集進行求解?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
成都創新互聯公司2013年成立,是專業互聯網技術服務公司,擁有項目成都網站設計、成都網站制作網站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元慶云做網站,已為上家服務,為慶云各地企業和個人服務,聯系電話:18980820575
java求解集合的子集的實例
方式1:我們知道子集個數 2的n次方
比如a,b,c的子集
* 000 0 {}
*001 1 a
*010 2 b
*011 3 a,b (b,a)
*100 4 c
* 101 5 a,c (c,a)
* 110 6 b,c (c,b)
* 111 7 a,b,c
利用二進制的對應關系
@Test public void test1() throws Exception { Set<ArrayList<Integer>> subsets = getSubsets( Arrays.asList(1,2,6)); Set<ArrayList<String>> subsets2 = getSubsets( Arrays.asList("a","b","c")); Set<ArrayList<Character>> subsets3 = getSubsets( Arrays.asList('b','c','d')); System.out.println(subsets); System.out.println(subsets2); System.out.println(subsets3); } //集合接受各種類型數據 public <T> Set<ArrayList<T>> getSubsets(List<T> subList) { //考慮去重 Set<ArrayList<T>> allsubsets = new LinkedHashSet<>(); int max = 1 << subList.size(); for (int loop = 0; loop < max; loop++) { int index = 0; int temp = loop; ArrayList <T> currentCharList = new ArrayList<T>(); //控制索引 while (temp > 0) { if ((temp & 1) > 0) { currentCharList.add(subList.get(index)); } temp >>= 1; index++; } allsubsets.add(currentCharList); } return allsubsets; }
方式2:歸納法
@Test public void testName() throws Exception { Set<List<Integer>> subsets2 = getSubsets2(Arrays.asList(1,2,3)); System.out.println(subsets2); } //方式2 歸納法 //從{}和最后一個元素開始,每次迭代加一個元素組成一個新的集合 public Set<List<Integer>> getSubsets2(List<Integer> list) { if (list.isEmpty()) { Set<List<Integer>> ans=new LinkedHashSet<>(); ans.add(Collections.emptyList()); return ans; } Integer first=list.get(0); List<Integer> rest=list.subList(1, list.size()); Set<List<Integer>> list1 = getSubsets2(rest); Set<List<Integer>> list2 = insertAll(first, list1);// System.out.println(list1); System.out.println(list2); System.out.println("================"); return concat(list1, list2); } public Set<List<Integer>> insertAll(Integer first,Set<List<Integer>> lists){ // Set<List<Integer>> result=new LinkedHashSet<>(); for (List<Integer> list : lists) { List<Integer> copy=new ArrayList<>(); copy.add(first); copy.addAll(list); result.add(copy); } return result; } //這樣寫可以不影響lists1,lists2的值 private Set<List<Integer>> concat(Set<List<Integer>> lists1,Set<List<Integer>> lists2) { Set<List<Integer>> temp=new LinkedHashSet<>(lists1); temp.addAll(lists2); return temp; }
關于利用java怎么對集合的子集進行求解問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。
當前標題:利用java怎么對集合的子集進行求解
URL網址:http://m.kartarina.com/article46/pipehg.html
成都網站建設公司_創新互聯,為您提供用戶體驗、App設計、網站改版、手機網站建設、虛擬主機、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯