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:
- The length of the given array will not exceed 15.
- The range of integer in the given array is [-100,100].
- The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
看到这道题目,就想起求集合的子集,子集长度最小为2,之前有在LintCode中做过Subset这道题目,感觉比较类似。
写了这些代码:
class Solution {
public:
void dfs(vector<int>nums,vector<vector<int>>&res,int endIndex,vector<int>&tmpres){
if (endIndex==nums.size()){
if (tmpres.size() >= 2) res.push_back(tmpres);
return;
}
int sameIndex = endIndex;
while (sameIndex!=0&&nums[sameIndex]==nums[endIndex]){
sameIndex--;
}
sameIndex++;
if (endIndex == 0) sameIndex = 0;
int l = endIndex - sameIndex;
if (l == 0 || (l<=tmpres.size()&&tmpres[tmpres .size()- l] == nums[endIndex])){
if (tmpres.empty() || tmpres[tmpres.size() - 1] <= nums[endIndex]){
tmpres.push_back(nums[endIndex]);
dfs(nums, res, endIndex + 1, tmpres);
tmpres.pop_back();
}
}
dfs(nums,res,endIndex+1,tmpres);
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>>res;
vector<int>tmpres;
dfs(nums,res,0,tmpres);
return res;
}
};
但是这个解法在[1,2,3,4,5,6,7,8,9,10,1,1,1,1,1]这个地方出错了,因为在判断重复元素的时候,是从当前元素向前进行判断,没有考虑到序列是一个无序的状态。那么对于[1,2,3,4,5,6,7,8,9,10,1,1,1,1,1]这个集合来说第一个1就会被忽略判断造成重复的序列。
发现leetcode和我思想差不多但是简单的解法(但也在[1,2,3,4,5,6,7,8,9,10,1,1,1,1,1]上出错了):
void dfs(vector<vector<int>>&res,vector<int>&seq,vector<int>&nums,int pos){
if (seq.size() > 1) res.push_back(seq);
unordered_set<int>hash;
for (int i = pos; i < nums.size(); i++){
if (seq.empty() || nums[i] >= seq.back() && hash.find(nums[i]) == hash.end()){
seq.push_back(nums[i]);
dfs(res,seq,nums,i+1);
seq.pop_back();
hash.insert(nums[i]);
}
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>>res;
vector<int>seq;
dfs(res,seq,nums,0);
return res;
}
100%accepted的Java解法
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> res= new HashSet<List<Integer>>();
List<Integer> holder = new ArrayList<Integer>();
findSequence(res, holder, 0, nums);
List result = new ArrayList(res);
return result;
}
public void findSequence(Set<List<Integer>> res, List<Integer> holder, int index, int[] nums) {
if (holder.size() >= 2) {
res.add(new ArrayList(holder));
}
for (int i = index; i < nums.length; i++) {
if(holder.size() == 0 || holder.get(holder.size() - 1) <= nums[i]) {
holder.add(nums[i]);
findSequence(res, holder, i + 1, nums);
holder.remove(holder.size() - 1);
}
}
}
}
总结:这题错的原因就是忽略了不连续的重复元素,怎么样处理它们