算法训练营day25(补),回溯5

package main

import "sort"

491. 非递减子序列

func findSubsequences(nums []int) [][]int {

  //存储全部集合

  result := make([][]int, 0)

  if len(nums) == 0 {

    return result

  }

  //存储单次集合

  path := make([]int, 0)

  var backtrace func(numList []int, startIndex int)

  backtrace = func(numList []int, startIndex int) {

    if len(path) > 1 {

      temp := make([]int, len(path))

      copy(temp, path)

      result = append(result, temp)

    }

    //记录数组每一个元素是否使用过

    user := make(map[int]bool, len(nums))

    for i := startIndex; i < len(numList); i++ {

      if user[numList[i]] {

        continue

      }

      if len(path) == 0 || numList[i] >= path[len(path)-1] {

        path = append(path, numList[i])

        user[numList[i]] = true

        backtrace(numList, i+1)

        //回溯处理

        path = path[:len(path)-1]

      }

    }

  }

  backtrace(nums, 0)

  return result

}

46. 全排列

func permute(nums []int) [][]int {

  //存储全部集合

  result := make([][]int, 0)

  if len(nums) == 0 {

    return result

  }

  //存储单次集合

  path := make([]int, 0)

  //记录数组每一个元素是否使用过

  user := make(map[int]bool, len(nums))

  var backtrace func(numList []int, user map[int]bool)

  backtrace = func(numList []int, user map[int]bool) {

    if len(path) == len(numList) {

      temp := make([]int, len(path))

      copy(temp, path)

      result = append(result, temp)

    }

    //因为是组合所有元素又要

    for i := 0; i < len(numList); i++ {

      if user[numList[i]] { //已用过的数直接跳过

        continue

      }

      path = append(path, numList[i])

      user[numList[i]] = true

      backtrace(numList, user)

      //回溯处理

      user[numList[i]] = false

      path = path[:len(path)-1]

    }

  }

  backtrace(nums, user)

  return result

}

47. 全排列 II

func permuteUnique(nums []int) [][]int {

  //存储全部集合

  result := make([][]int, 0)

  if len(nums) == 0 {

    return result

  }

  sort.Ints(nums)

  //存储单次集合

  path := make([]int, 0)

  //记录数组每一个元素是否使用过

  user := make(map[int]bool, len(nums))

  var backtrace func(numList []int, user map[int]bool)

  backtrace = func(numList []int, user map[int]bool) {

    if len(path) == len(numList) {

      temp := make([]int, len(path))

      copy(temp, path)

      result = append(result, temp)

    }

    for i := 0; i < len(numList); i++ {

      if i > 0 && numList[i] == numList[i-1] && user[i-1] == false { //过滤重复

        continue

      }

      if user[i] { //已用过的数直接跳过

        continue

      }

      path = append(path, numList[i])

      user[i] = true

      backtrace(numList, user)

      //回溯处理

      user[i] = false

      path = path[:len(path)-1]

    }

  }

  backtrace(nums, user)

  return result

}

你可能感兴趣的:(算法,数据结构,go)