題目描述
假設書本的疊放有這樣的規則,當A書的長度和寬度都大於B書時,可以將其B書置於A的上方,堆疊擺放,請設計一個程序,根據輸入的書本長寬,計算最多可以堆疊擺放多少本書?
輸入
[[16,15], [13, 12], [15, 14]]
輸出
3
說明
這里代表有3本書,第1本長寬分別為16和15,第2本長寬為13和12,第3本長寬為15和14,它們可以按照[13, 12],[15, 14],[16,15]
的順序堆疊,所以輸出3
動態規划,實質是求 最長遞增子序列,但本題有兩個因素需要考慮,可以通過排序將長度置為有序,這樣其實就是對寬度求最長遞增子序列,且可能存在長度相同的情況,在更新dp數組判定時,也要考慮到
package main import ( "fmt" "regexp" "sort" "strconv" ) type Book struct { Height int Width int } type books []Book func (b books) Len() int { return len(b) } func (b books) Swap(i,j int){ b[i],b[j] = b[j],b[i] } func (b books) Less(i,j int) bool{ if b[i].Height == b[j].Height{ return b[i].Width < b[j].Width } return b[i].Height < b[j].Height } func main() { input := "[[7, 11], [10, 9], [10, 11], [13, 12], [15, 14], [16,15]]" re := regexp.MustCompile("[0-9]+") numbers := re.FindAllString(input, -1) theBook := make(books,len(numbers)/2) for i:=0;i<len(numbers)/2;i++{ theBook[i].Height,_= strconv.Atoi(numbers[2*i]) theBook[i].Width,_= strconv.Atoi(numbers[2*i+1]) } sort.Sort(theBook) res := 1 dp := make([]int,len(theBook)) for k:= range dp{ dp[k]=1 } //動態規划 for i:=1;i<len(theBook);i++{ cur := theBook[i] for j:=0;j<i;j++{ pre := theBook[j] if cur.Height > pre.Height && cur.Width > pre.Width{ dp[i] = max(dp[i],dp[j]+1) } res = max(res,dp[i]) } } fmt.Println(res) } func max (x,y int) int{ if x > y{ return x }else { return y } }