소스 검색

AC 44 & 52

dengxinyi 6 년 전
부모
커밋
61544434af
3개의 변경된 파일75개의 추가작업 그리고 5개의 파일을 삭제
  1. 1 1
      hard/10.go
  2. 33 4
      hard/44.go
  3. 41 0
      hard/52.go

+ 1 - 1
hard/10.go

@@ -11,7 +11,7 @@ func isMatchRegex(s string, p string) bool {
 	}
 	// "" matches ""
 	match[0][0] = true
-	// Current & last char rank of pattern
+	// Current & last char index of pattern
 	currP, lastP := 1, 0
 	for currP <= len(p) {
 		zeroOrMore := false

+ 33 - 4
hard/44.go

@@ -1,9 +1,38 @@
 package main
 
+// ? any character; * any chatacter with any length
 func isMatch(s string, p string) (ans bool) {
-	return
+	m, n := len(s), len(p)
+	match := make([][]bool, m+1)
+	for i := range match {
+		match[i] = make([]bool, n+1)
+	}
+	match[0][0] = true
+	for i := 1; i <= n; i++ {
+		if p[i-1] == '*' {
+			match[0][i] = true
+		} else {
+			break
+		}
+	}
+	for y := 1; y <= m; y++ {
+		for x := 1; x <= n; x++ {
+			if s[y-1] == p[x-1] || p[x-1] == '?' {
+				match[y][x] = match[y-1][x-1]
+			} else if p[x-1] == '*' {
+				// Star matches empty string or matches next character
+				match[y][x] = match[y][x-1] || match[y-1][x]
+			}
+		}
+	}
+	return match[m][n]
 }
 
-func main() {
-	// Is it the same with no. 10??
-}
+// func main() {
+// 	println(isMatch("", ""))
+// 	println(isMatch("", "**"))
+// 	println(isMatch("aa", "a?"))
+// 	println(isMatch("aaa", "*"))
+// 	println(isMatch("cab", "c*b"))
+// 	println(isMatch("abc", "*c*a"))
+// }

+ 41 - 0
hard/52.go

@@ -0,0 +1,41 @@
+package main
+
+func totalNQueens(n int) (total int) {
+	putX := make([]int, n)
+	colLaid := make([]bool, n)
+	mainLaid := make([]bool, 2*n) // Range of y-x is [1-n, n-1], so y-x+n -> [1, 2n-1]
+	viceLaid := make([]bool, 2*n-1)
+	for y, x := 0, 0; ; { // The ith queen
+		for ; x < n; x++ {
+			if !(colLaid[x] || mainLaid[y-x+n] || viceLaid[x+y]) {
+				putX[y] = x
+				colLaid[x] = true
+				mainLaid[y-x+n] = true
+				viceLaid[x+y] = true
+				x = 0 // Next step
+				y++
+				break
+			}
+		}
+		if x == n || y == n { // Not valid or finished
+			if y == 0 { // If y is 0 and x is n, then all solutions are found
+				return
+			} else if y == n {
+				total++
+			}
+			y-- // Back tracking
+			x = putX[y]
+			colLaid[x] = false
+			mainLaid[y-x+n] = false
+			viceLaid[x+y] = false
+			x++
+		}
+	}
+}
+
+func main() {
+	println(totalNQueens(4))
+	println(totalNQueens(5))
+	println(totalNQueens(6))
+	println(totalNQueens(7))
+}