力扣算法 Java 刷题笔记【回溯算法篇 DFS】hot100(一)全排列 、子集 、组合 3

力扣算法 Java 刷题笔记【回溯算法篇 DFS】hot100(一)全排列 、子集 、组合 3,第1张

力扣算法 Java 刷题笔记【回溯算法篇 DFS】hot100(一)全排列子集 、组合 3

文章目录

1. 全排列(中等)2. 子集(中等)3. 组合(中等)

1. 全排列(中等)

地址: https://leetcode-cn.com/problems/permutations/
2021/01/23
做题反思

class Solution {
    List> res = new linkedList<>();
    public List> permute(int[] nums) {
        linkedList track = new linkedList<>();
        backtrack(nums, track);
        return res;
    }
    void backtrack(int[] nums, linkedList track) {
        if (track.size() == nums.length) {
            res.add(new linkedList(track));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (track.contains(nums[i])) {
                continue;
            }
            track.add(nums[i]);
            backtrack(nums, track);
            track.removeLast();
        }
    }
}

2. 子集(中等)

地址: https://leetcode-cn.com/problems/subsets/
2021/01/23
做题反思:

class Solution {
    List> res = new linkedList<>();
    public List> subsets(int[] nums) {
        linkedList track = new linkedList<>();
        backtrack(nums, track, 0);
        return res;
    }
    void backtrack(int[] nums, linkedList track, int start) {
        res.add(new linkedList(track));
        for (int i = start; i < nums.length; i++) {       
            track.add(nums[i]);
            backtrack(nums, track, i + 1);
            track.removeLast();
        }
    }
}

3. 组合(中等)

地址: https://leetcode-cn.com/problems/combinations/
2021/01/23
做题反思:

class Solution {
    List> res = new linkedList<>();
    public List> combine(int n, int k) {
        linkedList track = new linkedList<>();
        backtrack(n, k, track, 1);
        return res;
    }
    void backtrack(int n, int k, linkedList track, int start) {
        if (track.size() == k) {
            res.add(new linkedList(track));
            return;
        }
        for (int i = start; i <= n; i++) {
            if (track.contains(i)) {
                continue;
            }
            track.add(i);
            backtrack(n, k, track, i + 1);
            track.removeLast();
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5712212.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存