package main
import (
"fmt"
)
var zeros, ones int
func findMaxForm1(strs []string, m int, n int) int {
len := len(strs)
arr := make([][]int, len)
for i := 0; i < len; i++ {
zeroAndOne(strs[i])
arr[i] = []int{zeros, ones}
}
return process1(arr, 0, m, n)
}
func process1(arr [][]int, i int, z int, o int) int {
if i == len(arr) {
return 0
}
p1 := process1(arr, i+1, z, o)
p2 := 0
if arr[i][0] <= z && arr[i][1] <= o {
p2 = 1 + process1(arr, i+1, z-arr[i][0], o-arr[i][1])
}
if p1 > p2 {
return p1
}
return p2
}
func findMaxForm2(strs []string, m int, n int) int {
len := len(strs)
arr := make([][]int, len)
for i := 0; i < len; i++ {
zeroAndOne(strs[i])
arr[i] = []int{zeros, ones}
}
dp := make([][][]int, len)
for i := 0; i < len; i++ {
dp[i] = make([][]int, m+1)
for j := 0; j <= m; j++ {
dp[i][j] = make([]int, n+1)
for k := 0; k <= n; k++ {
dp[i][j][k] = -1
}
}
}
return process2(arr, 0, m, n, dp)
}
func process2(arr [][]int, i int, z int, o int, dp [][][]int) int {
if i == len(arr) {
return 0
}
if dp[i][z][o] != -1 {
return dp[i][z][o]
}
p1 := process2(arr, i+1, z, o, dp)
p2 := 0
if arr[i][0] <= z && arr[i][1] <= o {
p2 = 1 + process2(arr, i+1, z-arr[i][0], o-arr[i][1], dp)
}
ans := p1
if p2 > p1 {
ans = p2
}
dp[i][z][o] = ans
return ans
}
func findMaxForm3(strs []string, m int, n int) int {
len0 := len(strs)
dp := make([][][]int, len0+1)
for i := len0; i >= 0; i-- {
dp[i] = make([][]int, m+1)
for z := 0; z <= m; z++ {
dp[i][z] = make([]int, n+1)
}
}
for i := len0 - 1; i >= 0; i-- {
zeroAndOne(strs[i])
for z := 0; z <= m; z++ {
for o := 0; o <= n; o++ {
dp[i][z][o] = dp[i+1][z][o]
if zeros <= z && ones <= o {
dp[i][z][o] = max(dp[i][z][o], 1+dp[i+1][z-zeros][o-ones])
}
}
}
}
return dp[0][m][n]
}
func zeroAndOne(str string) {
zeros = 0
ones = 0
for i := 0; i < len(str); i++ {
if str[i] == '0' {
zeros++
} else {
ones++
}
}
}
func findMaxForm4(strs []string, m int, n int) int {
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for _, s := range strs {
zeroAndOne(s)
for i := m; i >= zeros; i-- {
for j := n; j >= ones; j-- {
dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1)
}
}
}
return dp[m][n]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
strs := []string{"10", "0001", "111001", "1", "0"}
m := 5
n := 3
res1 := findMaxForm1(strs, m, n)
fmt.Println("findMaxForm1:", res1)
res2 := findMaxForm2(strs, m, n)
fmt.Println("findMaxForm2:", res2)
res3 := findMaxForm3(strs, m, n)
fmt.Println("findMaxForm3:", res3)
res4 := findMaxForm4(strs, m, n)
fmt.Println("findMaxForm4:", res4)
}
评论