leetcode打卡-回溯I

77. 组合

leetcode题目链接:https://leetcode.cn/problems/combinations/

leetcode AC记录:

代码如下:

public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        hs(res, path, 1, k,n);
        return res;
    }

    public void hs(List<List<Integer>> res, List<Integer> path, int begin, int k, int n) {
        if(path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = begin; i <= n;i++) {
            path.add(i);
            hs(res, path, i+1, k, n);
            path.remove(path.size()-1);
        }
    }

216.组合总和III

leetcode题目链接:https://leetcode.cn/problems/combination-sum-iii

leetcode AC记录:

代码如下:

 public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        combain(res, path, 0, k, n, 1);
        return res;
    }

    public void combain(List<List<Integer>> res, List<Integer> path, int sum, int k, int n, int begin) {
        if(sum == n && path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = begin;i <= 9;i++) {
            path.add(i);
            combain(res, path, sum+i, k, n, i + 1);
            path.remove(path.size()-1);
        }
    }

17.电话号码的字母组合

leetcode题目链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/

leetcode AC记录:

代码如下:

class Solution {
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0) {
            return new ArrayList<>(0);
        }
        List<String> res = new ArrayList<>(16);
        String path = "";
        hs(res, path, 0, digits.length(), 0, digits);
        return res;
    }

    public void hs(List<String> res, String path, int curSize, int size, int beginNum, String digits) {
        if(curSize == size) {
            res.add(path);
            return;
        }

        char c = digits.charAt(beginNum);
        char[] str = getArray(c);
        for(int i = 0;i < str.length;i++) {
            hs(res, path + str[i], curSize + 1, size, beginNum + 1, digits);
        }
    }

    public char[] getArray(char c) {
        switch(c) {
            case '2':
                return "abc".toCharArray();
            case '3':
                return "def".toCharArray();
            case '4':
                return "ghi".toCharArray();
            case '5':
                return "jkl".toCharArray();
            case '6':
                return "mno".toCharArray();
            case '7':
                return "pqrs".toCharArray();
            case '8':
                return "tuv".toCharArray();
            case '9':
                return "wxyz".toCharArray();
        }
        return null;
    }
}

39.组合总和

leetcode题目链接:https://leetcode.cn/problems/combination-sum

leetcode AC记录:

代码如下:

public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        reverse(res, path, candidates, target, 0, 0);
        return res;
    }

    public void reverse(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int begin, int sum) {
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        } else if(sum > target) {
            return;
        }

        for(int i = begin;i < candidates.length;i++) {
            // while(sum <= target) {
                path.add(candidates[i]);
                reverse(res, path, candidates, target, i, sum + candidates[i]);
                path.remove(path.size()-1);
            // }
        }
    }

 40. 组合总和 II

leetcode题目链接:https://leetcode.cn/problems/combination-sum-ii/

leetcode AC记录:

思路:去重分两部分,一个是数组需要先进行排序,第二个是使用数组记录递归中同一层的相同元素是否已经使用,如果已经使用,则说明两个元素相同,都参与了结果组成,如果不相同,则说明当前元素和之前元素相同,是相同的结果集,跳过不处理。

代码如下:

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        Arrays.sort(candidates);
        System.out.println(Arrays.toString(candidates));
        boolean[] used = new boolean[candidates.length];
        combain(res, used, path, candidates, target, 0, 0);
        return res;
    }

    public void combain(List<List<Integer>> res, boolean[] used,List<Integer> path, int[] candidates, int target, int sum, int begin) {
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        } else if(sum > target) {
            return;
        }


        for(int i = begin; i < candidates.length; i++) {
            if(i > 0 && candidates[i] == candidates[i-1] && !used[i-1]) {
                continue;
            }

            path.add(candidates[i]);
            used[i] = true;
            combain(res, used, path, candidates, target, sum + candidates[i], i + 1);
            used[i] = false;
            path.remove(path.size()-1);
        }
    }

131. 分割回文字符串

leetcode题目链接:https://leetcode.cn/problems/palindrome-partitioning 

leetcode AC记录:

思路:使用begin当作要切割的起点,使用i表示切割的长度,进行回溯即可。

代码如下:

public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>(16);
        List<String> path = new ArrayList<>(16);
        reverse(res, path, 0, s, 0);
        return res;
    }


    public void reverse(List<List<String>> res, List<String> path, int length, String s, int begin) {
        if(length >= s.length()) {
            res.add(new ArrayList<>(path));
        }

        for(int i = 0;i < s.length();i++) {
            if(begin + i + 1 > s.length()) {
                continue;
            }
            String str = s.substring(begin, begin + i + 1);
            if(isHuiwen(str)) {
                path.add(str);
                reverse(res, path, begin + i + 1, s, begin + i + 1);
                path.remove(path.size()-1);
            }
        }
    }

    public boolean isHuiwen(String str) {
        int begin = 0;
        int end = str.length()-1;
        while(begin <= end) {
            if(str.charAt(begin) != str.charAt(end)) {
                return false;
            }
            begin++;
            end--;
        }

        return true;
    }

93.复原IP地址

leetcode题目链接:https://leetcode.cn/problems/restore-ip-addresses/

leetcode AC记录:

思路:使用begin代表需要分割的开始位置,i代表分割的长度,如果path链表长度超过4,直接返回。

代码如下:

public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>(16);
        List<String> path = new ArrayList<>(16);
        huisu(s, res, path, 0, 0);
        return res;
    }

    public void huisu(String s, List<String> res, List<String> path, int begin, int length) {
        if(length == s.length() && path.size() == 4) {
            res.add(path.stream().collect(Collectors.joining(".")));
            return;
        } else if(length > s.length()  || path.size() > 4) {
            return;
        }

        for(int i = 0;i < s.length();i++) {
            if(begin + i + 1 > s.length()) {
                continue;
            }
            int num = isValid(s.substring(begin, begin + i + 1));
            if(num != -1) {
                path.add(String.valueOf(num));
                huisu(s, res, path, begin + i +1, begin + i + 1);
                path.remove(path.size()-1);
            }
        }
    }


    //返回-1说明不合法
    public int isValid(String s) {
        //判断首位是否为0
        boolean zeroFisrst = s.charAt(0) == '0';
        if(zeroFisrst && s.length() > 1) {
            return -1;
        }
        //判断是否为纯数字
        int res = 0;
        int js = 1;
        for(int i = s.length() -1; i >= 0 ;i--) {
            char c = s.charAt(i);
            if('0' > c || c > '9') {
                return -1;
            }

            res += js * (c - '0');
            js *= 10;
        }

        return res >= 0 && res <= 255 ? res : -1;
    }

78.子集

leetcode题目链接:https://leetcode.cn/problems/subsets/ 

leetcode AC记录:

代码如下:

public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);

        huisu(res, path, nums, 0);
        return res;
    }

    public void huisu(List<List<Integer>> res, List<Integer> path, int[] nums, int begin) {
        if(path.size() <= nums.length) {
            res.add(new ArrayList<>(path));
        }

        for(int i = begin;i < nums.length;i++) {
            path.add(nums[i]);
            huisu(res, path, nums, i + 1);
            path.remove(path.size()-1);
        }
    }

90.子集II

leetcode题目链接:https://leetcode.cn/problems/subsets-ii/submissions 

leetcode AC记录:

代码如下:

public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        hs(res, path, nums, used, 0);
        return res;
    }

    public void hs(List<List<Integer>> res, List<Integer> path, int[] nums, boolean[] used, int begin) {
        if(path.size() <= nums.length) {
            res.add(new ArrayList<>(path));
        }

        for(int i = begin;i < nums.length;i++) {
            if(i > 0 && nums[i-1] == nums[i] && !used[i-1]) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            hs(res, path, nums, used, i + 1);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }

 491.递增子序列

leetcode题目链接:https://leetcode.cn/problems/non-decreasing-subsequences

leetcode AC 记录: 

思路:回溯同一层中不能有重复的,使用set进行去重。

代码如下:

public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);

        hs(res, path, nums, 0);
        return res;
    }

    public void hs(List<List<Integer>> res, List<Integer> path, int[] nums, int begin) {
        if(path.size() > 1) {
            res.add(new ArrayList<>(path));
        }

        Set<Integer> set = new HashSet<>(16);       
        for(int i = begin;i < nums.length;i++) {
            if(set.contains(nums[i])) {
                continue;
            }

            if(path.size() == 0 || path.get(path.size()-1) <= nums[i]) {
                set.add(nums[i]);
                path.add(nums[i]);
                hs(res, path, nums, i + 1);
                path.remove(path.size()-1);

            }
        }
    }

 46.全排列

leetcode题目链接:https://leetcode.cn/problems/permutations/

leetcode AC记录:

思路:回溯的时候,使用数组记录是否已经使用过,都是从0开始遍历。

代码如下:

public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        boolean[] used = new boolean[nums.length];
        hs(res, path, nums, used);
        return res;
    }

    public void hs(List<List<Integer>> res, List<Integer> path, int[] nums, boolean[] used) {
        if(path.size() >= nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < nums.length;i++) {
            if(used[i]) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            hs(res, path, nums, used);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }

 47.全排列 II

leetcode题目链接:https://leetcode.cn/problems/permutations-ii

leetcode AC记录:

思路:使用数组记录有没有使用过,去重使用数组排序,如果回溯的本层将要使用的元素和下标减1位置处的元素相同,代表是重复的结果集,跳过不处理。

代码如下:

 public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>(16);
        List<Integer> path = new ArrayList<>(16);
        boolean[] used = new boolean[nums.length];
        Arrays.sort(nums);
        hs(res, path, nums, used);
        return res;
    }

    public void hs(List<List<Integer>> res, List<Integer> path, int[] nums, boolean[] used) {
        if(path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = 0;i < nums.length;i++) {
            if(used[i]) {
                continue;
            }

            if(i > 0 && nums[i-1] == nums[i] && !used[i-1]) {
                continue;
            }

            used[i] = true;
            path.add(nums[i]);
            hs(res, path, nums, used);
            path.remove(path.size()-1);
            used[i] = false;
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值