1 问题
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
输入: [4, 6, 7, 7] 输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
给定数组的长度不会超过15。
数组中的整数范围是 [-100,100]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
2 解法
在09 子集II(leecode 90)中我们是通过排序,再加一个标记数组来达到去重的目的。
而本题求自增子序列,是不能对原数组进行排序的,排完序的数组都是自增子序列了。「所以不能使用之前的去重逻辑!」
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex)
{
//满足题中:递增子序列的长度至少是2的条件
if(path.size() >= 2)
res.push_back(path);
// 注意这里不要加return,因为要取树上的所有节点
//定义数组,记录元素在本层是否使用过
//整数范围为[-100, 100]
int used[201] = {
0};
for(int i = startIndex; i < nums.size(); i++)
{
//去重,去除非递增情况
if(!path.empty() && nums[i] < path.back() || used[nums[i] + 100] == 1)
continue;
path.push_back(nums[i]);
used[nums[i] + 100] = 1; // 记录这个元素在本层用过了,本层后面不能再用了
//递归
backtracking(nums, i + 1);
//回溯
path.pop_back();
}
}
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums, 0);
return res;
}
};