Skip to main content

Combinations

Definition​

The Combinations Algorithm generates all possible combinations of elements from a given set without considering the order of elements

Practice​

generateCombinations(set, targetSize, currentCombination, index, results)
if size of currentCombination is equal to targetSize
add currentCombination to results
return
end if

if index is equal to size of set
return
end if

// Include the current element
add set[index] to currentCombination
generateCombinations(set, targetSize, currentCombination, index + 1, results)

// Exclude the current element
remove set[index] from currentCombination
generateCombinations(set, targetSize, currentCombination, index + 1, results)

end function

// Example usage:
results = []
set = [1, 2, 3, 4]
targetSize = 2
generateCombinations(set, targetSize, [], 0, results)
print results