Leetcode - Maximum Length of Pair Chain
Leetcode - Partition to K Equal Sum Subsets

Leetcode - Increasing Subsequences

violet posted @ May 28, 2020 08:45:30 AM in 算法 with tags Algorithm Golang backtracking , 280 阅读

https://leetcode.com/problems/increasing-subsequences/

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2.

Example:

Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

 

Note:

  1. The length of the given array will not exceed 15.
  2. The range of integer in the given array is [-100,100].
  3. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

 

func findSubsequences(nums []int) [][]int {
    result := [][]int{}
    backtrack(nums, &[]int{}, &result, 0)
    set := [][]int{}
    for _, r := range result {
        if !contains(set, r) {
            set = append(set, r)
        }
    }
    return set
}

func backtrack(nums []int, tmp *[]int, result *[][]int, start int) {
    if len(*tmp) >= 2 {
        copied := make([]int, len(*tmp))
        copy(copied, *tmp)
        *result = append(*result, copied)
    }
    for i := start; i < len(nums); i++ {
        if len(*tmp) == 0 || (len(*tmp) > 0 && (*tmp)[len(*tmp)-1] <= nums[i]) {
            *tmp = append(*tmp, nums[i])
            backtrack(nums, tmp, result, i+1)
            *tmp = (*tmp)[:len(*tmp)-1]
        }
    }
}

func contains(arr [][]int, nums []int) bool {
    for _, a := range arr {
        if len(a) != len(nums) {
            continue
        }
        equal := true
        for i := 0; i < len(a); i++ {
            if a[i] != nums[i] {
                equal = false
                break
            }
        }
        if equal {
            return true
        }
    }
    return false
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter