dengxinyi 6 tahun lalu
induk
melakukan
7728b55084
2 mengubah file dengan 76 tambahan dan 0 penghapusan
  1. 40 0
      medium/638.shopping-offers.go
  2. 36 0
      medium/640.solve-the-equation.go

+ 40 - 0
medium/638.shopping-offers.go

@@ -0,0 +1,40 @@
+func shoppingOffers(price []int, special [][]int, needs []int) int {
+	var need [6]int
+	copy(need[:], needs)
+	m := make(map[[6]int]int)
+	return buy(price, special, need, m) // DFS
+}
+
+func buy(price []int, special [][]int, need [6]int, m map[[6]int]int) int {
+	if v, ok := m[need]; ok {
+		return v
+	}
+	res := 0
+	for i := range price {
+		res += need[i] * price[i]
+	} // The price without special offer
+	for _, s := range special {
+		var n [6]int
+		copy(n[:], need[:])
+		i := 0
+		for ; i < len(price); i++ {
+			n[i] -= s[i]
+			if n[i] < 0 {
+				break
+			}
+		}
+		if i == len(price) {
+			res = minInt(res, s[i]+buy(price, special, n, m))
+		}
+	}
+	m[need] = res
+	return res
+}
+
+func minInt(x, y int) int {
+	if x < y {
+		return x
+	}
+	return y
+}
+

+ 36 - 0
medium/640.solve-the-equation.go

@@ -0,0 +1,36 @@
+func solveEquation(equation string) string {
+	part := strings.Split(equation, "=")
+	x1, a1 := parse(part[0])
+	x2, a2 := parse(part[1])
+	if x1 == x2 && a1 == a2 {
+		return "Infinite solutions"
+	} else if x1 != x2 {
+		return fmt.Sprintf("x=%d", (a2-a1)/(x1-x2))
+	} else {
+		return "No solution"
+	}
+}
+
+func parse(eq string) (x int, a int) {
+	pre, n := 0, len(eq)
+	for i := range eq {
+		if eq[i] == 'x' || i == n-1 || eq[i+1] == '-' || eq[i+1] == '+' {
+			if eq[i] == 'x' {
+				switch eq[pre:i] {
+				case "", "+": // Handle special case
+					x += 1
+				case "-":
+					x -= 1
+				default:
+					num, _ := strconv.Atoi(eq[pre:i])
+					x += num
+				}
+			} else {
+				num, _ := strconv.Atoi(eq[pre : i+1])
+				a += num
+			}
+			pre = i + 1
+		}
+	}
+	return
+}