题目地址:
https://www.lintcode.com/problem/increasing-subsequences/description
给定一个整数数组,求其所有长度大于等于 2 2 2的(非严格)上升子序列。注意返回答案里不要包含完全相同的两个序列。
思路是DFS。主要难点在于去重。如果直接DFS,逐个枚举每个数字是否能加入path,当遇到形如 ( 2 , 3 , 2 , 4 ) (2,3,2,4) (2,3,2,4)这样的数组的时候, ( 2 , 4 ) (2,4) (2,4)会被枚举两次(枚举第一个 2 2 2的时候会枚举到这个path,枚举第二个 2 2 2的时候也会枚举到这个path)。这两个 2 2 2并不紧挨着,所以这里去重需要借助哈希表。枚举完一个数之后,就将其加入哈希表,下次遇到哈希表里存在的数字的时候就直接跳过。代码如下:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
/**
* @param nums: an integer array
* @return: all the different possible increasing subsequences of the given array
*/
public List<List<Integer>> findSubsequences(int[] nums) {
// Write your code here
List<List<Integer>> res = new ArrayList<>();
dfs(0, nums, new ArrayList<>(), res);
return res;
}
private void dfs(int pos, int[] nums, List<Integer> path, List<List<Integer>> res) {
// 将长度大于等于2的上升子序列加入答案
if (path.size() >= 2) {
res.add(new ArrayList<>(path));
}
// 枚举完了,返回
if (pos == nums.length) {
return;
}
Set<Integer> set = new HashSet<>();
for (int i = pos; i < nums.length; i++) {
if (set.contains(nums[i])) {
continue;
}
set.add(nums[i]);
if (path.isEmpty() || nums[i] >= path.get(path.size() - 1)) {
path.add(nums[i]);
dfs(i + 1, nums, path, res);
// 回溯的时候恢复现场
path.remove(path.size() - 1);
}
}
}
}
时间复杂度 O ( n 2 n ) O(n2^n) O(n2n)(一共有最多 2 n 2^n 2n个答案,每个答案深拷贝一份需要 O ( n ) O(n) O(n)),空间 O ( n ) O(n) O(n)。