第二十七天 | 回溯算法

第二十七天,继续回溯算法

 

39. 组合总和

class Solution {
    List<Integer> list = new ArrayList<>();
    List<List<Integer>> ans = new ArrayList<>();
    int target;
    int len;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.target = target;
        len = candidates.length;
        backTracking(0, candidates, 0);
        return ans;
    }
    public void backTracking(int sum, int[] candidates, int index){
        if(sum > target){
            return;
        }
        if(sum == target){
            ans.add(new ArrayList<>(list));
            return;
        }

        for(int i = index; i < len; i++){
            list.add(candidates[i]);
            backTracking(sum + candidates[i], candidates, i);
            list.remove(list.size() - 1);
        }
    }
}

很典型的回溯

40.组合总和II

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> list =new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates,target,0);
        return result;
    }
    private void backTracking(int[] candidates, int target, int start) {
        if (target < 0) {
            return;
        }

        if (target == 0) {
            result.add(new ArrayList<Integer>(list));
            return;
        }

        for (int i = start; i < candidates.length; ++i) {
            int one = candidates[i];
            list.add(one);
            backTracking(candidates,target-one,i+1);
            list.remove(list.size()-1);
        
            while (i < candidates.length -1 && candidates[i] == candidates[i+1]) ++i;
        }
    }
}

需要再加一步去重

131.分割回文串

class Solution {
    List<List<String>> lists = new ArrayList<>();
    Deque<String> deque = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backTracking(s, 0);
        return lists;
    }

    private void backTracking(String s, int startIndex) {
        //如果起始位置大于s的大小,说明找到了一组分割方案
        if (startIndex >= s.length()) {
            lists.add(new ArrayList(deque));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            //如果是回文子串,则记录
            if (isPalindrome(s, startIndex, i)) {
                String str = s.substring(startIndex, i + 1);
                deque.addLast(str);
            } else {
                continue;
            }
            //起始位置后移,保证不重复
            backTracking(s, i + 1);
            deque.removeLast();
        }
    }
    //判断是否是回文串
    private boolean isPalindrome(String s, int startIndex, int end) {
        for (int i = startIndex, j = end; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}

这道题属于不太会的

 

今天的两道模版题,和一道不是很会的题

posted @ 2022-11-08 15:17  小猫Soda  阅读(24)  评论(0)    收藏  举报