Print all possible combinations in an array (which may have duplicate elements) of 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 outputs {/* 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 <Integer> ret1 = new 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 <Integer> ret2 = new ArrayList <Integer> (); collections. sort (set2); rec2 (set2, r2, 0, ret2, new ArrayList <Integer> (); System. out. println (ret2);} // solution 1: analysis: the output is available. The first element added to al is selected cyclically, and then the subinterval is reduced, recursive processing of subproblems // first is the first element currently processing subintervals public static void rec (ArrayList <Integer> set, int r, int first, arrayList <Integer> ret, ArrayList <Integer> al) {if (al. size () = r) {// exit condition: Exit ret when the number in al reaches r. add (new ArrayList <Integer> (al); return ;}for (int I = first; I <set. size (); I ++) {// from the first element of the subinterval to the last element will have the opportunity to be added to the al if (I + 1 <set. size () & set. get (I + 1) = set. get (I) {// Skip duplicate elements, but check whether the row is out of bounds;} al. add (set. get (I); // note that the parameters used in the for loop are I rather than firstrec (set, r, I + 1, ret, al ); // shorten the subinterval by 1 distance to al. remove (al. size ()-1) ;}}// solution 2: select or do not select an element public static void rec2 (ArrayList <Integer> set, int r, int first, arrayList <Integer> ret, ArrayList <Integer> al) {if (r = al. size () {// exit condition: when the number of ALS reaches r, ret can be exited. add (new ArrayList <Integer> (al); return;} if (first> = set. size () {// return if the first traversal exceeds the set capacity;} while (first + 1 <set. size () & set. get (first + 1) = set. get (first) {// skip repeated elements, but check whether the cross-border first ++;} rec2 (set, r, first + 1, ret, al ); // do not select the current element al. add (set. get (first); // select the current element 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/