Parcourir la source

add 添加全排列 II

tangs il y a 2 ans
Parent
commit
d9b47ebfc1

+ 67 - 0
leetcode/tags/array/全排列 II/main.go

@@ -0,0 +1,67 @@
+/*
+暴力剪枝,优化方案是先排序,相同数字跳过
+*/
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"strconv"
+	"strings"
+)
+
+func main() {
+	var result [][]int
+	var nums []int
+	input := bufio.NewScanner(os.Stdin)
+
+	for input.Scan() {
+		line := input.Text()
+		values := strings.Split(line, " ")
+		nums = []int{}
+		for _, v := range values {
+			digit, _ := strconv.Atoi(v)
+			nums = append(nums, digit)
+		}
+
+		result = permuteUnique(nums)
+
+		fmt.Println(len(result), result)
+	}
+}
+
+func permuteUnique(nums []int) [][]int {
+	if len(nums) == 1 {
+		return [][]int{nums}
+	}
+
+	var record = map[string]bool{}
+	var result = [][]int{}
+	var length = len(nums)
+	var key string
+	var newNums = append([]int{}, nums...)
+	for i := 0; i < length; i++ {
+		newNums = append([]int{}, nums...)
+		var digit = newNums[i]
+		newNums[i] = newNums[0]
+		newNums[0] = digit
+
+		temps := permuteUnique(newNums[1:])
+
+		for _, v := range temps {
+			key = ""
+			for _, tempV := range v {
+				key = key + fmt.Sprintf("%d", tempV)
+			}
+			if _, ok := record[key]; ok {
+				continue
+			}
+			record[key] = true
+			result = append(result, append([]int{newNums[0]}, v...))
+		}
+
+	}
+
+	return result
+}

+ 71 - 0
leetcode/tags/array/全排列 II/main_optimize.go

@@ -0,0 +1,71 @@
+/*
+暴力剪枝,优化方案是先排序,相同数字跳过
+*/
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"strconv"
+	"strings"
+)
+
+func main() {
+	var result [][]int
+	var nums []int
+	input := bufio.NewScanner(os.Stdin)
+
+	for input.Scan() {
+		line := input.Text()
+		values := strings.Split(line, " ")
+		nums = []int{}
+		for _, v := range values {
+			digit, _ := strconv.Atoi(v)
+			nums = append(nums, digit)
+		}
+
+		result = permuteUnique(nums)
+
+		fmt.Println(len(result), result)
+	}
+
+	// nums = []int{2, 2, 1, 1}
+	// result = permuteUnique(nums)
+
+	// fmt.Println()
+
+}
+
+func permuteUnique(nums []int) [][]int {
+	return permute(nums)
+}
+
+func permute(nums []int) [][]int {
+	if len(nums) == 1 {
+		return [][]int{nums}
+	}
+
+	var result = [][]int{}
+	var length = len(nums)
+	var newNums = append([]int{}, nums...)
+	var record = map[int]bool{}
+	for i := 0; i < length; i++ {
+		if _, ok := record[nums[i]]; ok {
+			continue
+		}
+		record[nums[i]] = true
+		newNums = append([]int{}, nums...)
+		var digit = newNums[i]
+		newNums[i] = newNums[0]
+		newNums[0] = digit
+		temps := permute(newNums[1:])
+
+		for _, v := range temps {
+			result = append(result, append([]int{newNums[0]}, v...))
+		}
+
+	}
+
+	return result
+}