问题描述
来源:LeetCode第491题
难度:中等
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中至少有两个元素 。你可以按任意顺序返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
示例2:
输入:nums = [4,4,3,2,1]
输出:[[4,4]]
-
1 <= nums.length <= 15
-
-100 <= nums[i] <= 100
问题分析
这题让找出数组中的所有递增子序列,和前面讲的全排列 II非常类似。他们都是有重复的元素,但前面一题为了过滤掉重复的结果,需要先对数组进行排序,而这题是求子序列,所以不能排序。
我们可以使用回溯算法,并且在同一层级,相同的数字只能选择一次,所以我们可以使用set集合来记录每层的节点,剪掉重复的分支。
为什么相同层级不能选择重复的数字,很好理解,因为每个数字都有选和不选两种状态,如果有相同的数字,当前面一个数字不选择的时候,这个结果和后面一个数字选择时候,他们的结果是一样的,出现了重复,我们只需要把后面这个剪掉即可,如下图所示。
C语言
void dfs(int **ans, int *path, int count, int *nums, int numsSize, int *returnSize,
int **returnColumnSizes, int index) {
if (count > 1) {
ans[*returnSize] = malloc(count * sizeof(int));
memcpy(ans[*returnSize], path, count * sizeof(int));
(*returnColumnSizes)[(*returnSize)++] = count;
}
// 记录当前层并且具有共同父节点的所有节点,不能有重复的。
int *set = calloc(201, sizeof(int));
for (int i = index; i < numsSize; i++) {
int key = nums[i] + 100;
if (set[key]) // 跳过重复的
continue;
set[key] = 1;
// 必须是非递减的才可以选择
if (count == 0 || nums[i] >= path[count - 1]) {
path[count++] = nums[i];
dfs(ans, path, count, nums, numsSize, returnSize, returnColumnSizes, i + 1);
count--;
}
}
free(set);
}
int **findSubsequences(int *nums, int numsSize, int *returnSize, int **returnColumnSizes) {
int **ans = malloc(100000 * sizeof(int *));
int *path = malloc(15 * sizeof(int));
*returnSize = 0;
*returnColumnSizes = malloc(100000 * sizeof(int));
dfs(ans, path, 0, nums, numsSize, returnSize, returnColumnSizes, 0);
return ans;
}