dengxinyi 6 năm trước cách đây
mục cha
commit
1d6946ea5c
2 tập tin đã thay đổi với 78 bổ sung0 xóa
  1. 30 0
      medium/304.range-sum-query-2d-immutable.go
  2. 48 0
      medium/306.additive-number.go

+ 30 - 0
medium/304.range-sum-query-2d-immutable.go

@@ -0,0 +1,30 @@
+type NumMatrix struct {
+	acc [][]int
+}
+
+func Constructor(matrix [][]int) (numMat NumMatrix) { // Constructor O(n^2), SumRegion O(1)
+	rows := len(matrix)
+	if rows == 0 {
+		return
+	}
+	cols := len(matrix[0])
+	numMat.acc = make([][]int, rows+1)
+	for i := 0; i <= rows; i++ {
+		numMat.acc[i] = make([]int, cols+1)
+		for sum, j := 0, 1; i != 0 && j <= cols; j++ {
+			sum += matrix[i-1][j-1] // sum is the sum of curr row
+			numMat.acc[i][j] = sum + numMat.acc[i-1][j] // accumulate curr col
+		}
+	}
+	return
+}
+
+func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) (sum int) {
+	return this.acc[row2+1][col2+1] - this.acc[row2+1][col1] - this.acc[row1][col2+1] + this.acc[row1][col1]
+}
+
+/**
+ * Your NumMatrix object will be instantiated and called as such:
+ * obj := Constructor(matrix);
+ * param_1 := obj.SumRegion(row1,col1,row2,col2);
+ */

+ 48 - 0
medium/306.additive-number.go

@@ -0,0 +1,48 @@
+func isAdditiveNumber(num string) bool {
+	n := len(num)
+	if n < 3 { // At least 3 chars
+		return false
+	}
+	for i := 1; i < (n+1)/2; i++ {
+		if num[0] == '0' && i != 1 { // Avoid 00 + ...
+			return false
+		}
+		for j := 1; j <= (n-i)/2; j++ {
+			if num[i] == '0' && j != 1 { // Avoid ... + 0x
+				break
+			}
+			var one, two int
+			fmt.Sscan(num[0:i], &one)
+			fmt.Sscan(num[i:i+j], &two)
+			if search(num, i+j, one, two) {
+				return true
+			}
+		}
+	}
+	return false
+}
+
+func search(num string, idx, one, two int) bool {
+	n := len(num)
+	if idx == n {
+		return true
+	} else if num[idx] == '0' {
+		if one+two != 0 {
+			return false
+		}
+		return search(num, idx+1, 0, 0) // 00000000... is valid
+	}
+	var three int
+	for three = 0; three < one+two && idx < n; idx++ {
+		three = three*10 + int(num[idx]-'0')
+	}
+	if three == one+two {
+		return search(num, idx, two, three)
+	}
+	return false
+}
+
+type pair struct {
+	_1 int
+	_2 int
+}