引言
LeetCode 上的第491题“递增子序列”是一个典型的回溯问题。这个问题要求找出给定数组内所有可能的递增子序列。回溯算法是一种通过试错的方式,逐步逼近问题解的方法。本文将介绍如何使用 Java 的回溯算法解决这个问题。
题目描述
给定一个整数数组 nums
,找出所有可能的递增子序列(子序列的元素呈严格递增顺序)。返回长度为 k
的递增子序列的数目。
示例:
输入: [1,2,3,4]
输出: 5
解释:
所有可能的递增子序列是:
- [1]
- [2]
- [3]
- [4]
- [1, 2, 3]
说明:
1 <= len(nums) <= 1000
问题分析
这个问题可以通过回溯算法来解决。我们从左到右遍历数组,每次选择一个数字,并将其添加到当前递增子序列中。
Java 实现
以下是使用 Java 解决这个问题的代码实现:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public int findSubsequences(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, 0);
return result.size();
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int start) {
if (tempList.size() > 0 && tempList.get(tempList.size() - 1) > nums[start]) {
// 剪枝:如果当前数字比路径上的最后一个数字大,则停止添加
return;
}
// 将当前的临时路径添加到结果中
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
if (tempList.isEmpty() || nums[i] > tempList.get(tempList.size() - 1)) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3, 4};
int count = solution.findSubsequences(nums);
System.out.println("Number of increasing subsequences: " + count);
}
}
代码解释
- findSubsequences 方法:这是主方法,接收数组
nums
,返回所有递增子序列的数量。 - backtrack 方法:这是一个递归方法,用于实现回溯算法。
result
:存储所有递增子序列的列表。tempList
:当前的递增子序列。nums
:原始数组。start
:当前遍历到的数组索引。
- 剪枝:如果当前数字比路径上的最后一个数字大,则没有必要继续添加,因为子序列需要严格递增。
结语
通过本文的介绍,你应该已经了解了如何使用 Java 的回溯算法解决 LeetCode 第491题“递增子序列”。这个问题考查了回溯算法的应用,通过递归和剪枝可以有效减少不必要的搜索。希望本文能够帮助你更好地理解和掌握回溯算法。如果你有任何问题或需要进一步的帮助,请随时在评论区提问。