mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-19 06:50:59 +00:00
Add ru version (#1865)
* Add Russian docs site baseline * Add Russian localized codebase * Polish Russian code wording * Update ru code translation. * Update code translation and chapter covers. * Fix pythontutor extraction. * Add README and landing page. * placeholder of profiles * Use figures of English version * Remove chapter paperbook
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
// File: n_queens.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Алгоритм бэктрекинга: n ферзей */
|
||||
func backtrack(row, n int, state *[][]string, res *[][][]string, cols, diags1, diags2 *[]bool) {
|
||||
// Когда все строки уже обработаны, записать решение
|
||||
if row == n {
|
||||
newState := make([][]string, len(*state))
|
||||
for i, _ := range newState {
|
||||
newState[i] = make([]string, len((*state)[0]))
|
||||
copy(newState[i], (*state)[i])
|
||||
|
||||
}
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Обойти все столбцы
|
||||
for col := 0; col < n; col++ {
|
||||
// Вычислить главную и побочную диагонали, соответствующие этой клетке
|
||||
diag1 := row - col + n - 1
|
||||
diag2 := row + col
|
||||
// Отсечение: в столбце, главной диагонали и побочной диагонали этой клетки не должно быть ферзей
|
||||
if !(*cols)[col] && !(*diags1)[diag1] && !(*diags2)[diag2] {
|
||||
// Попытка: поставить ферзя в эту клетку
|
||||
(*state)[row][col] = "Q"
|
||||
(*cols)[col], (*diags1)[diag1], (*diags2)[diag2] = true, true, true
|
||||
// Перейти к размещению следующей строки
|
||||
backtrack(row+1, n, state, res, cols, diags1, diags2)
|
||||
// Откат: восстановить эту клетку как пустую
|
||||
(*state)[row][col] = "#"
|
||||
(*cols)[col], (*diags1)[diag1], (*diags2)[diag2] = false, false, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Решить задачу о n ферзях */
|
||||
func nQueens(n int) [][][]string {
|
||||
// Инициализировать доску размера n*n, где 'Q' обозначает ферзя, а '#' — пустую клетку
|
||||
state := make([][]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
row := make([]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
row[i] = "#"
|
||||
}
|
||||
state[i] = row
|
||||
}
|
||||
// Отмечать, есть ли ферзь в столбце
|
||||
cols := make([]bool, n)
|
||||
diags1 := make([]bool, 2*n-1)
|
||||
diags2 := make([]bool, 2*n-1)
|
||||
res := make([][][]string, 0)
|
||||
backtrack(0, n, &state, &res, &cols, &diags1, &diags2)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// File: n_queens_test.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNQueens(t *testing.T) {
|
||||
n := 4
|
||||
res := nQueens(n)
|
||||
|
||||
fmt.Println("Размер входной доски =", n)
|
||||
fmt.Println("Количество способов расстановки ферзей:", len(res))
|
||||
for _, state := range res {
|
||||
fmt.Println("--------------------")
|
||||
for _, row := range state {
|
||||
fmt.Println(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// File: permutation_test.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestPermutationI(t *testing.T) {
|
||||
/* Все перестановки I */
|
||||
nums := []int{1, 2, 3}
|
||||
fmt.Printf("Входной массив nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
res := permutationsI(nums)
|
||||
fmt.Printf("Все перестановки res = ")
|
||||
fmt.Println(res)
|
||||
}
|
||||
|
||||
func TestPermutationII(t *testing.T) {
|
||||
nums := []int{1, 2, 2}
|
||||
fmt.Printf("Входной массив nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
res := permutationsII(nums)
|
||||
fmt.Printf("Все перестановки res = ")
|
||||
fmt.Println(res)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// File: permutations_i.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Алгоритм бэктрекинга: все перестановки I */
|
||||
func backtrackI(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
|
||||
// Когда длина состояния равна числу элементов, записать решение
|
||||
if len(*state) == len(*choices) {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
}
|
||||
// Перебор всех вариантов выбора
|
||||
for i := 0; i < len(*choices); i++ {
|
||||
choice := (*choices)[i]
|
||||
// Отсечение: нельзя выбирать один и тот же элемент повторно
|
||||
if !(*selected)[i] {
|
||||
// Попытка: сделать выбор и обновить состояние
|
||||
(*selected)[i] = true
|
||||
*state = append(*state, choice)
|
||||
// Перейти к следующему выбору
|
||||
backtrackI(state, choices, selected, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
(*selected)[i] = false
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Все перестановки I */
|
||||
func permutationsI(nums []int) [][]int {
|
||||
res := make([][]int, 0)
|
||||
state := make([]int, 0)
|
||||
selected := make([]bool, len(nums))
|
||||
backtrackI(&state, &nums, &selected, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// File: permutations_ii.go
|
||||
// Created Time: 2023-05-14
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Алгоритм бэктрекинга: все перестановки II */
|
||||
func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
|
||||
// Когда длина состояния равна числу элементов, записать решение
|
||||
if len(*state) == len(*choices) {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
}
|
||||
// Перебор всех вариантов выбора
|
||||
duplicated := make(map[int]struct{}, 0)
|
||||
for i := 0; i < len(*choices); i++ {
|
||||
choice := (*choices)[i]
|
||||
// Отсечение: нельзя выбирать один и тот же элемент повторно и нельзя повторно выбирать равные элементы
|
||||
if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
|
||||
// Попробовать: сделать выбор, обновить состояние
|
||||
// Записать значение уже выбранного элемента
|
||||
duplicated[choice] = struct{}{}
|
||||
(*selected)[i] = true
|
||||
*state = append(*state, choice)
|
||||
// Перейти к следующему выбору
|
||||
backtrackII(state, choices, selected, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
(*selected)[i] = false
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Все перестановки II */
|
||||
func permutationsII(nums []int) [][]int {
|
||||
res := make([][]int, 0)
|
||||
state := make([]int, 0)
|
||||
selected := make([]bool, len(nums))
|
||||
backtrackII(&state, &nums, &selected, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// File: preorder_traversal_i_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Предварительный обход: пример 1 */
|
||||
func preOrderI(root *TreeNode, res *[]*TreeNode) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
if (root.Val).(int) == 7 {
|
||||
// Записать решение
|
||||
*res = append(*res, root)
|
||||
}
|
||||
preOrderI(root.Left, res)
|
||||
preOrderI(root.Right, res)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// File: preorder_traversal_ii_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Предварительный обход: пример 2 */
|
||||
func preOrderII(root *TreeNode, res *[][]*TreeNode, path *[]*TreeNode) {
|
||||
if root == nil {
|
||||
return
|
||||
}
|
||||
// Попытка
|
||||
*path = append(*path, root)
|
||||
if root.Val.(int) == 7 {
|
||||
// Записать решение
|
||||
*res = append(*res, append([]*TreeNode{}, *path...))
|
||||
}
|
||||
preOrderII(root.Left, res, path)
|
||||
preOrderII(root.Right, res, path)
|
||||
// Откат
|
||||
*path = (*path)[:len(*path)-1]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// File: preorder_traversal_iii_compact.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Предварительный обход: пример 3 */
|
||||
func preOrderIII(root *TreeNode, res *[][]*TreeNode, path *[]*TreeNode) {
|
||||
// Отсечение
|
||||
if root == nil || root.Val == 3 {
|
||||
return
|
||||
}
|
||||
// Попытка
|
||||
*path = append(*path, root)
|
||||
if root.Val.(int) == 7 {
|
||||
// Записать решение
|
||||
*res = append(*res, append([]*TreeNode{}, *path...))
|
||||
}
|
||||
preOrderIII(root.Left, res, path)
|
||||
preOrderIII(root.Right, res, path)
|
||||
// Откат
|
||||
*path = (*path)[:len(*path)-1]
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// File: preorder_traversal_iii_template.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
/* Проверить, является ли текущее состояние решением */
|
||||
func isSolution(state *[]*TreeNode) bool {
|
||||
return len(*state) != 0 && (*state)[len(*state)-1].Val == 7
|
||||
}
|
||||
|
||||
/* Записать решение */
|
||||
func recordSolution(state *[]*TreeNode, res *[][]*TreeNode) {
|
||||
*res = append(*res, append([]*TreeNode{}, *state...))
|
||||
}
|
||||
|
||||
/* Проверить, допустим ли этот выбор в текущем состоянии */
|
||||
func isValid(state *[]*TreeNode, choice *TreeNode) bool {
|
||||
return choice != nil && choice.Val != 3
|
||||
}
|
||||
|
||||
/* Обновить состояние */
|
||||
func makeChoice(state *[]*TreeNode, choice *TreeNode) {
|
||||
*state = append(*state, choice)
|
||||
}
|
||||
|
||||
/* Восстановить состояние */
|
||||
func undoChoice(state *[]*TreeNode, choice *TreeNode) {
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
|
||||
/* Алгоритм бэктрекинга: пример 3 */
|
||||
func backtrackIII(state *[]*TreeNode, choices *[]*TreeNode, res *[][]*TreeNode) {
|
||||
// Проверить, является ли текущее состояние решением
|
||||
if isSolution(state) {
|
||||
// Записать решение
|
||||
recordSolution(state, res)
|
||||
}
|
||||
// Перебор всех вариантов выбора
|
||||
for _, choice := range *choices {
|
||||
// Отсечение: проверить допустимость выбора
|
||||
if isValid(state, choice) {
|
||||
// Попытка: сделать выбор и обновить состояние
|
||||
makeChoice(state, choice)
|
||||
// Перейти к следующему выбору
|
||||
temp := make([]*TreeNode, 0)
|
||||
temp = append(temp, choice.Left, choice.Right)
|
||||
backtrackIII(state, &temp, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
undoChoice(state, choice)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// File: preorder_traversal_i_compact_test.go
|
||||
// Created Time: 2023-05-09
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestPreorderTraversalICompact(t *testing.T) {
|
||||
/* Инициализация двоичного дерева */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nИнициализация двоичного дерева")
|
||||
PrintTree(root)
|
||||
|
||||
// Предварительный обход
|
||||
res := make([]*TreeNode, 0)
|
||||
preOrderI(root, &res)
|
||||
|
||||
fmt.Println("\nВсе узлы со значением 7")
|
||||
for _, node := range res {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIICompact(t *testing.T) {
|
||||
/* Инициализация двоичного дерева */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nИнициализация двоичного дерева")
|
||||
PrintTree(root)
|
||||
|
||||
// Предварительный обход
|
||||
path := make([]*TreeNode, 0)
|
||||
res := make([][]*TreeNode, 0)
|
||||
preOrderII(root, &res, &path)
|
||||
|
||||
fmt.Println("\nВсе пути от корня к узлу 7")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIIICompact(t *testing.T) {
|
||||
/* Инициализация двоичного дерева */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nИнициализация двоичного дерева")
|
||||
PrintTree(root)
|
||||
|
||||
// Предварительный обход
|
||||
path := make([]*TreeNode, 0)
|
||||
res := make([][]*TreeNode, 0)
|
||||
preOrderIII(root, &res, &path)
|
||||
|
||||
fmt.Println("\nВсе пути от корня к узлу 7, не содержащие узлов со значением 3")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreorderTraversalIIITemplate(t *testing.T) {
|
||||
/* Инициализация двоичного дерева */
|
||||
root := SliceToTree([]any{1, 7, 3, 4, 5, 6, 7})
|
||||
fmt.Println("\nИнициализация двоичного дерева")
|
||||
PrintTree(root)
|
||||
|
||||
// Алгоритм бэктрекинга
|
||||
res := make([][]*TreeNode, 0)
|
||||
state := make([]*TreeNode, 0)
|
||||
choices := make([]*TreeNode, 0)
|
||||
choices = append(choices, root)
|
||||
backtrackIII(&state, &choices, &res)
|
||||
|
||||
fmt.Println("\nВсе пути от корня к узлу 7, не содержащие узлов со значением 3")
|
||||
for _, path := range res {
|
||||
for _, node := range path {
|
||||
fmt.Printf("%v ", node.Val)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// File: subset_sum_i.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Алгоритм бэктрекинга: сумма подмножеств I */
|
||||
func backtrackSubsetSumI(start, target int, state, choices *[]int, res *[][]int) {
|
||||
// Если сумма подмножества равна target, записать решение
|
||||
if target == 0 {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Обойти все варианты выбора
|
||||
// Отсечение 2: начинать обход с start, чтобы избежать генерации повторяющихся подмножеств
|
||||
for i := start; i < len(*choices); i++ {
|
||||
// Отсечение 1: если сумма подмножества превышает target, немедленно завершить цикл
|
||||
// Это связано с тем, что массив уже отсортирован, следующие элементы больше, и сумма подмножества точно превысит target
|
||||
if target-(*choices)[i] < 0 {
|
||||
break
|
||||
}
|
||||
// Попытка: сделать выбор и обновить target и start
|
||||
*state = append(*state, (*choices)[i])
|
||||
// Перейти к следующему выбору
|
||||
backtrackSubsetSumI(i, target-(*choices)[i], state, choices, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Решить задачу суммы подмножеств I */
|
||||
func subsetSumI(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // Состояние (подмножество)
|
||||
sort.Ints(nums) // Отсортировать nums
|
||||
start := 0 // Стартовая вершина обхода
|
||||
res := make([][]int, 0) // Список результатов (список подмножеств)
|
||||
backtrackSubsetSumI(start, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// File: subset_sum_i_naive.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
/* Алгоритм бэктрекинга: сумма подмножеств I */
|
||||
func backtrackSubsetSumINaive(total, target int, state, choices *[]int, res *[][]int) {
|
||||
// Если сумма подмножества равна target, записать решение
|
||||
if target == total {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Перебор всех вариантов выбора
|
||||
for i := 0; i < len(*choices); i++ {
|
||||
// Отсечение: если сумма подмножества превышает target, пропустить этот выбор
|
||||
if total+(*choices)[i] > target {
|
||||
continue
|
||||
}
|
||||
// Попытка: сделать выбор и обновить элемент и total
|
||||
*state = append(*state, (*choices)[i])
|
||||
// Перейти к следующему выбору
|
||||
backtrackSubsetSumINaive(total+(*choices)[i], target, state, choices, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Решить задачу суммы подмножеств I (с повторяющимися подмножествами) */
|
||||
func subsetSumINaive(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // Состояние (подмножество)
|
||||
total := 0 // Сумма подмножеств
|
||||
res := make([][]int, 0) // Список результатов (список подмножеств)
|
||||
backtrackSubsetSumINaive(total, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// File: subset_sum_ii.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import "sort"
|
||||
|
||||
/* Алгоритм бэктрекинга: сумма подмножеств II */
|
||||
func backtrackSubsetSumII(start, target int, state, choices *[]int, res *[][]int) {
|
||||
// Если сумма подмножества равна target, записать решение
|
||||
if target == 0 {
|
||||
newState := append([]int{}, *state...)
|
||||
*res = append(*res, newState)
|
||||
return
|
||||
}
|
||||
// Обойти все варианты выбора
|
||||
// Отсечение 2: начинать обход с start, чтобы избежать генерации повторяющихся подмножеств
|
||||
// Отсечение 3: начинать обход с start, чтобы избежать повторного выбора одного и того же элемента
|
||||
for i := start; i < len(*choices); i++ {
|
||||
// Отсечение 1: если сумма подмножества превышает target, немедленно завершить цикл
|
||||
// Это связано с тем, что массив уже отсортирован, следующие элементы больше, и сумма подмножества точно превысит target
|
||||
if target-(*choices)[i] < 0 {
|
||||
break
|
||||
}
|
||||
// Отсечение 4: если этот элемент равен элементу слева, значит ветвь поиска повторяется, ее нужно сразу пропустить
|
||||
if i > start && (*choices)[i] == (*choices)[i-1] {
|
||||
continue
|
||||
}
|
||||
// Попытка: сделать выбор и обновить target и start
|
||||
*state = append(*state, (*choices)[i])
|
||||
// Перейти к следующему выбору
|
||||
backtrackSubsetSumII(i+1, target-(*choices)[i], state, choices, res)
|
||||
// Откат: отменить выбор и восстановить предыдущее состояние
|
||||
*state = (*state)[:len(*state)-1]
|
||||
}
|
||||
}
|
||||
|
||||
/* Решить задачу суммы подмножеств II */
|
||||
func subsetSumII(nums []int, target int) [][]int {
|
||||
state := make([]int, 0) // Состояние (подмножество)
|
||||
sort.Ints(nums) // Отсортировать nums
|
||||
start := 0 // Стартовая вершина обхода
|
||||
res := make([][]int, 0) // Список результатов (список подмножеств)
|
||||
backtrackSubsetSumII(start, target, &state, &nums, &res)
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// File: subset_sum_test.go
|
||||
// Created Time: 2023-06-24
|
||||
// Author: Reanon (793584285@qq.com)
|
||||
|
||||
package chapter_backtracking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
. "github.com/krahets/hello-algo/pkg"
|
||||
)
|
||||
|
||||
func TestSubsetSumINaive(t *testing.T) {
|
||||
nums := []int{3, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumINaive(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", входной массив nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("Все подмножества с суммой " + strconv.Itoa(target) + ": res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
fmt.Println("Обратите внимание: результат этого метода содержит повторяющиеся множества")
|
||||
}
|
||||
|
||||
func TestSubsetSumI(t *testing.T) {
|
||||
nums := []int{3, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumI(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", входной массив nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("Все подмножества с суммой " + strconv.Itoa(target) + ": res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubsetSumII(t *testing.T) {
|
||||
nums := []int{4, 4, 5}
|
||||
target := 9
|
||||
res := subsetSumII(nums, target)
|
||||
|
||||
fmt.Printf("target = " + strconv.Itoa(target) + ", входной массив nums = ")
|
||||
PrintSlice(nums)
|
||||
|
||||
fmt.Println("Все подмножества с суммой " + strconv.Itoa(target) + ": res = ")
|
||||
for i := range res {
|
||||
PrintSlice(res[i])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user