瀏覽代碼

add 添加全排列

tangs 2 年之前
父節點
當前提交
f3a896ef34
共有 1 個文件被更改,包括 52 次插入0 次删除
  1. 52 0
      leetcode/tags/array/全排列/main.go

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

@@ -0,0 +1,52 @@
+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 = permute(nums)
+		fmt.Println(len(result), result)
+	}
+
+}
+func permute(nums []int) [][]int {
+	if len(nums) == 1 {
+		return [][]int{nums}
+	}
+
+	var result = [][]int{}
+	var length = len(nums)
+	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 := permute(newNums[1:])
+		for _, v := range temps {
+			result = append(result, append([]int{newNums[0]}, v...))
+		}
+
+	}
+
+	return result
+}