func LexicographicPermute(n int) [][]int {

	var results [][]int
	perm := common.GenerateNumbers(n)

	results = append(results, perm)

	findIJ := func(perm []int) (i, j int) {
		i = -1
		j = -1
		for k := 0; k < len(perm)-1; k++ {
			if perm[k] < perm[k+1] {
				i = k
			}
			if i != -1 && perm[k+1] > perm[i] {
				j = k + 1
			}
		}
		return
	}

	i, j := findIJ(perm)
	fmt.Println(perm, i, j)
	for i != -1 {
		perm = append([]int(nil), perm...)
		common.SwapElement(perm, i, j)
		common.ReverseSliceRange(perm, i+1, n-1)
		results = append(results, perm)
		i, j = findIJ(perm)
		fmt.Println(perm, i, j)
	}

	return results
}
Exemple #2
0
func main() {
	n := 5
	elems := common.GenerateNumbers(n)
	// fmt.Println(elems)

	flags := common.GenerateFlagNumbers(n) // 1,2,4,8....
	count := common.Power(2, n)

	allSubsets := [][]int{}
	for i := 0; i < count; i++ {
		subset := []int{}
		for k, flag := range flags {
			if i&flag != 0 {
				subset = append(subset, elems[k])
			}
		}
		allSubsets = append(allSubsets, subset)
	}

	for _, subset := range allSubsets {
		fmt.Println(subset)
	}
}