go语言leetcode训练 NO.654,NO.22

这两题的思路是一样的 都是一个递归函数+一个辅助函数

辅助函数用于为下一次递归提供元素,验证这次递归是否可行等功能

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

  1. 二叉树的根是数组中的最大元素。
  2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func constructMaximumBinaryTree(nums []int) *TreeNode {
       node :=&TreeNode{0,nil,nil}
       max,left_nums,right_nums,ok:=findmax(nums)
       if ok!=nil{
              return nil
          }else{
              node.Val   = max
              node.Left  = constructMaximumBinaryTree(left_nums)
              node.Right = constructMaximumBinaryTree(right_nums)
          }
       return node

}

func findmax(nums []int)(int,[]int,[]int,error){
       //fmt.Println("d")
       if len(nums)==0{
              return 0,[]int{},[]int{},errors.New("empty nums")
          }else if len(nums)==1{
              return nums[0],[]int{},[]int{},nil
          }
       max:=nums[0]
       index :=0
       for i:=1;i<len(nums);i++  {
              if nums[i]>max{
                     max = nums[i]
                     index = i
                 }
          }
       return max,append([]int{},nums[:index]...),append([]int{},nums[index+1:]...),nil
}

 

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

验证的条件:

1.当‘(’数量等于n时只能返回‘)’

2.当‘(’数量<n 且 数量>=‘)’数量时,可以返回‘(’,‘)’

3.当一个string长度==n*2时,表示一种可能已经形成,存入[]string 最终返回值中

func generateParenthesis1(n int) []string {
   return_str :=[]string{}
   getstrem("",n,&return_str)
   return return_str
}

func getstrem(str string,n int,result *[]string)(poss string){
   new_poss := ""
   if len(str)==n*2{
      *result = append(*result,str)
   }
   get_poss,ok := check(str,n)
   if ok==nil{
      for _,poss_em := range get_poss {
         new_poss = str + poss_em
         //fmt.Println(new_poss)
         poss = getstrem(new_poss,n,result)
      }
   }

   return new_poss
}

func check(str string,n int)([]string,error){
   left_nums  :=0
   right_nums :=0
   for i:=0;i<len(str);i++ {
      if str[i]=='('{
         left_nums++
      }
      if str[i]==')'{
         right_nums++
      }
   }
   if left_nums==0&&right_nums==0{
      return []string{"("},nil
   }
   if left_nums==n && left_nums>right_nums {
      return []string{")"},nil
   }
   if left_nums<n && left_nums>=right_nums {
      return []string{")","("},nil
   }
   return nil,errors.New("'('is enough")
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值