Skip to content

Instantly share code, notes, and snippets.

@TiberiuGC
Created September 20, 2023 07:44
Show Gist options
  • Save TiberiuGC/0d8e5035793e1cc7ec8d1068ecab99fc to your computer and use it in GitHub Desktop.
Save TiberiuGC/0d8e5035793e1cc7ec8d1068ecab99fc to your computer and use it in GitHub Desktop.
nCr Generator
package main
import "fmt"
// GenerateCombinations generates all combinations of choosing k elements from a set of n elements
func GenerateCombinations(n, k int) [][]int {
combinations := [][]int{}
helper(n, k, []int{}, &combinations)
return combinations
}
func helper(n, k int, current []int, combinations *[][]int) {
if k == 0 {
*combinations = append(*combinations, current)
return
}
if n == 0 {
return
}
// Exclude current element
helper(n-1, k, current, combinations)
// Include current element
current = append([]int{n}, current...)
helper(n-1, k-1, append([]int{}, current...), combinations)
}
func main() {
n := 5
k := 3
allCombinations := GenerateCombinations(n, k)
fmt.Println(allCombinations)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment