Thursday, August 20, 2020

491. Increasing Subsequences -----------M ~~~!!!!!

 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]]

 

Constraints:

  • 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.

A:

哎,这个题,我的错误比较多

思路依然是DP,每次加入一个,然后添加2个的。 再添加上之前所有的结果后面添加刚加入的。

class Solution {
public:
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        vector<vector<int>> res;
        unordered_map<int, int> Count;
        for (int end = 0; end < nums.size(); end++) {
            int b = nums[end];
            int preResCount = res.size();
            // add for length 2,  (note before end, there could be some duplicates
            auto iter = Count.begin();
            while (iter != Count.end()) {
                if (((iter->first < b) && (Count[b] == 0)) || ((iter->first == b) && (Count[b] == 1))) {
                    res.push_back(vector<int>{iter->first, b});
                }
                iter++;
            }
            // now append all that's already in result
            for (int i = 0; i < preResCount; i++) {
                if (res[i].back() > b)
                    continue;
                // check last Count[b] are all b
                if (res[i].size() < Count[b])
                    continue;
                bool allB = true;
                for (int j = res[i].size() - 1; j >= int(res[i].size()) - Count[b]; j--) {
                    if (res[i][j] != b) {
                        allB = false;
                        break;
                    }
                }
                if (allB) {
                    vector<int> tmp = res[i];
                    tmp.push_back(b);
                    res.push_back(tmp);
                }
            }
            Count[b]++;
        }
        return res;
    }
};


Errors: 

1:  一开始添加 2个长度的时候, 没考虑a 重复的情况

2: 很诡异的, 迄今也不明白。 for (int j = res[i].size() - 1; j >= int(res[i].size()) - Count[b]; j--) {}

必须转成int类型。 否则       j 有时候会变成1   ,  即使   j >=0

3: 一开始,没有把 nums[0] 放入Count中。  哎,

No comments:

Post a Comment