Combination
Combination
COMBINATIONS
Introduction
Example: In a card game, we have to deal 5 cards out of the pack consisting of 52
cards. We have no interest in the order in which the 5 cards were selected. Rather, we
only care which cards are present in the hand
Program: Given an array of size n, generate and print all possible combinations of r
elements in array. For example, if input array is {1, 2, 3, 4} and r is 2, then output
should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.
COMBINATIONS
Technique-1
We create a temporary array ‘data’ which stores all outputs one by one.
Start with the first index in data, one by one fix elements at this index and recur for
remaining indexes.
We first fix 1 at index 0 in data then recur for remaining indexes, then we fix 2 at index
0 and recur.
Technique-1
COMBINATIONS
If input array is [1 , 2, 1] and r is 2, then the program prints [1, 2] and [2, 1] as
two different combinations
import java.util.Arrays;
Program
comb1.java
Technique-2
We one by one consider every element of input array, and recur for two
cases:
Program
comb2.java
Program
comb3.java
System.out.print(data[j]+" ");
https://
learn.codemithra.com