Given an integer array
The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.
Example 1:
Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
Example 2:
Input: nums = [4,4,3,2,1] Output: [[4,4]]
Constraints:
1 <= nums.length <= 15 -100 <= nums[i] <= 100
Solution
以 [4,1,2,3,4] 為例,在 Subsets II 那題,[4,1,2,3] 和 [1,2,3,4] 是一樣的
所以必須先 sort 然後配合 set 來過濾
但在這題,因為是要找 increasing 的 subsequence
所以 [4,1,2,3] 是不會出現的,在過濾條件中就會直接被過濾
因為是要求排列組合,所以用DFS來解
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
val ans = mutableListOf<List<Int>>() | |
fun findSubsequences(nums: IntArray): List<List<Int>> { | |
dfs(0, nums, emptyList()) | |
return ans | |
} | |
fun dfs(start: Int, nums: IntArray, cmb: List<Int>) { | |
if(cmb.size > 1) { | |
ans.add(cmb) | |
} | |
val set = mutableSetOf<Int>() | |
for(i in start..nums.lastIndex) { | |
if((cmb.isNotEmpty() && nums[i] < cmb.last()) || set.contains(nums[i])) { | |
continue | |
} | |
set.add(nums[i]) | |
dfs(i+1, nums, cmb+listOf(nums[i])) | |
} | |
} | |
} |
沒有留言:
張貼留言