# 無名

## 给定一个数n如23121;给定一组数字a如[2 4 9]求由a中元素组成的小于n的最大数

 1 package main
2
3 import (
4     "fmt"
5     "strings"
6 )
7 func main() {
8     num := 45543
9     dstArr := []string{"4","9","2"}
10     numList := strings.Split(fmt.Sprintf("%d",num),"")
11     ret := solution2(numList,dstArr,false)
12     fmt.Println(ret)
13 }
14
15 // 23121
16 // [2,4,9]
17 func solution2(num []string, arr []string, pre bool) []string {
18     if len(num) == 1 && !pre {
19         ret := lastNum(num[0],arr)
20         if len(ret) == 0 {
21             return []string{}
22         }
23         return []string{ret}
24     } else if len(num) == 1 {
25         return []string{maxNum(arr)}
26     }
27     def := make([]string, 0)
28     curNun := num[0]
29     if pre {
30         def = append(def,maxNum(arr))
31         def = append(def,solution2(num[1:], arr, pre)...)
32         return def
33     }
34     e := equNum(curNun,arr)
35     ret1 := make([]string, 0)
36     if len(e) != 0 {
37         ret := solution2(num[1:], arr, pre)
38         if len(ret) > 0 {
39             ret1 = append(ret1,e)
40             ret1 = append(ret1,ret...)
41         }
42     }
43     m := lastNum(curNun,arr)
44     ret2 := make([]string, 0)
45     if len(m) != 0 {
46         ret := solution2(num[1:], arr, true)
47         if len(ret) > 0 {
48             ret2 = append(ret2,m)
49             ret2 = append(ret2,ret...)
50         }
51     }
52     ret3 := solution2(num[1:], arr, true)
53     if len(ret1) > 0 {
54         return ret1
55     } else if len(ret2) > 0 {
56         return ret2
57     }
58     return ret3
59
60 }
61
62 func maxNum(arr []string) string{
63     var p string
64     for _, item :=range arr {
65         if p < item {
66             p = item
67         }
68     }
69     return p
70 }
71
72 func lastNum(n string, arr []string) string{
73     var last string
74     for _, item :=range arr {
75         if item < n && last < item {
76             last = item
77         }
78     }
79     return last
80 }
81
82 func equNum(n string, arr []string) string{
83     for _, item :=range arr {
84         if item == n  {
85             return item
86         }
87     }
88     return ""
89 }

posted on 2023-09-07 04:08  xiezhengcai  阅读(464)  评论(0编辑  收藏  举报