491.increasing-subsequences.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. type none struct{}
  2. func findSubsequencesDP(nums []int) (ans [][]int) {
  3. dp := make([][]int, 0)
  4. set := make(map[string]none)
  5. for _, i := range nums {
  6. for _, a := range dp {
  7. if a[len(a)-1] <= i {
  8. arr := append(a, i)
  9. key := arr2str(arr)
  10. if _, ok := set[key]; !ok {
  11. dp = append(dp, arr)
  12. ans = append(ans, arr)
  13. set[key] = none{}
  14. }
  15. }
  16. }
  17. key := arr2str([]int{i})
  18. if _, ok := set[key]; !ok {
  19. dp = append(dp, []int{i})
  20. set[key] = none{}
  21. }
  22. }
  23. return
  24. }
  25. func arr2str(arr []int) string {
  26. var sb strings.Builder
  27. for _, i := range arr {
  28. sb.WriteString(strconv.Itoa(i))
  29. sb.WriteRune(',')
  30. }
  31. return sb.String()
  32. }
  33. func findSubsequencesDFS(nums []int) (ans [][]int) {
  34. dfs(nums, len(nums), 0, make([]int, 0), &ans)
  35. return
  36. }
  37. func dfs(nums []int, n int, s int, cur []int, ans *[][]int) {
  38. set := make(map[int]bool)
  39. for i := s; i < n; i++ {
  40. if l := len(cur); l != 0 && nums[i] < cur[l-1] {
  41. continue
  42. } else if _, ok := set[nums[i]]; ok {
  43. continue
  44. }
  45. set[nums[i]] = true
  46. nxt := append(cur, nums[i])
  47. if 2 <= len(nxt) {
  48. *ans = append(*ans, nxt)
  49. }
  50. dfs(nums, n, i+1, nxt, ans)
  51. }
  52. }