算法修炼Day29|491.递增子序列 * 46.全排列 * 47.全排列 II

79 阅读1分钟

LeetCode:491. 递增子序列 - 力扣(LeetCode)

1.思路

回溯方法三部曲: 确定回溯方法参数及其返回值;确定单层递归的逻辑;确定终止条件。

2.代码实现
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> findSubsequences(int[] nums) {

        backTracking(nums, 0);
        return result;
    }
    void backTracking(int[] nums, int startIndex) {
        // 终止条件
        if (path.size() >= 2) {
            result.add(new ArrayList<>(path));
        }

        Set<Integer> set = new HashSet<>(); // 用来树层去重
        // 遍历
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && path.get(path.size() - 1) > nums[i] || set.contains(nums[i])) {
                continue;
            }
            set.add(nums[i]);
            path.add(nums[i]);
            backTracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
3.复杂度分析

时间复杂度:O(n * 2^n).

空间复杂度:O().

LeetCode:46. 全排列 - 力扣(LeetCode)

1.思路

回溯三部曲:确定回溯方法参数及其返回值;确定中止条件;确定单层递归的逻辑。

2.代码实现
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {

        backTracking(nums, path);
        return result;
    }
    void backTracking(int[] nums, List<Integer> path) {
        // 终止条件
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
        }
        // 遍历:单层递归逻辑
        for (int i = 0; i < nums.length; i++) {
            if (path.contains(nums[i])) {
                continue;
            }
            path.add(nums[i]);
            backTracking(nums, path);
            path.remove(path.size() - 1);
        }
    }
}
3.复杂度分析

时间复杂度:O(n * n!).

空间复杂度:O(n).

LeetCode:47. 全排列 II - 力扣(LeetCode)

1.思路

有点背模板的感觉,很奇怪的难受。。。

2.代码实现
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();     
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        backTracking(nums, used);
        return result;
    }
    void backTracking(int[] nums, boolean[] used) {
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            // 如果同一树枝nums[i]没有使用过开始处理
            if (used[i] == false) {
                used[i] = true; // 标记同一数值nums[i]使用过,防止同一树枝去重使用
                path.add(nums[i]);
                backTracking(nums, used);
                path.remove(path.size() - 1); // 回溯,说明同一树层nums[i]使用过,防止下一树层重复
                used[i] = false; // 回溯
            }
        }
    }
}
3.复杂度分析

时间复杂度:O(n * n!).

空间复杂度:O(n).