-
-
Save TiberiuGC/0d8e5035793e1cc7ec8d1068ecab99fc to your computer and use it in GitHub Desktop.
nCr Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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