列印出大小為n的數組(可能有重複元素)裡所有可能的組合
Input:
{1, 2, 3, 4}, r=2
Output:
{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.
package recursion;import java.util.ArrayList;import java.util.Collections;public class Print_all_possible_combinations_of_r_elements_in_a_given_array_of_size_n {/* Input: {1, 2, 3, 4}, r=2 Output: {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}. */public static void main(String[] args) {int[] s1 = {1, 2, 3, 4};ArrayList<Integer> set1 = new ArrayList<Integer>();for (int i : s1) {set1.add(i);}int r1 = 2;ArrayList<ArrayList<Integer>> ret1 = new ArrayList<ArrayList<Integer>>();rec2(set1, r1, 0, ret1, new ArrayList<Integer>());System.out.println(ret1);int[] s2 = {1, 2, 1, 3, 2};ArrayList<Integer> set2 = new ArrayList<Integer>();for (int i : s2) {set2.add(i);}int r2 = 2;ArrayList<ArrayList<Integer>> ret2 = new ArrayList<ArrayList<Integer>>();Collections.sort(set2);rec2(set2, r2, 0, ret2, new ArrayList<Integer>());System.out.println(ret2);}// 解法一:分析:觀察output可得,先迴圈選定添加到al的第一個元素,然後縮小子區間,遞迴處理子問題// first是當前處理子區間的第一個元素public static void rec(ArrayList<Integer> set, int r, int first, ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> al) {if(al.size() == r) {// 允出準則:當al裡的數量達到r時即可退出ret.add(new ArrayList<Integer>(al));return;}for(int i=first; i<set.size(); i++) {// 從子區間的第一個元素到最後一個元素都有機會被添加到al中 if(i+1<set.size() && set.get(i+1) == set.get(i)) {// 跳過重複元素,但要檢查是否越界continue;}al.add(set.get(i));// 注意在for迴圈內,用到的參數是i而不是firstrec(set, r, i+1, ret, al);// 縮短子區間1個距離al.remove(al.size()-1);}}// 解法二:選擇或者不選擇某個元素public static void rec2(ArrayList<Integer> set, int r, int first, ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> al) {if(r == al.size()) {// 允出準則:當al裡的數量達到r時即可退出ret.add(new ArrayList<Integer>(al));return;}if(first >= set.size()) {// 當first遍曆超過set容量時也要返回return;}while(first+1<set.size() && set.get(first+1) == set.get(first)) {// 跳過重複元素,但要檢查是否越界first++;}rec2(set, r, first+1, ret, al);// 不選擇當前元素al.add(set.get(first));// 選擇當前元素rec2(set, r, first+1, ret, al);al.remove(al.size()-1);}}
http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/