代码随想录算法训练营第二十七天|39 组合总和 40 组合总和II 131分割回文串

目录

39 组合总和

40 组合总和II

131 分割回文串


39 组合总和

class Solution {
    List>res = new ArrayList<>();
    ListnewList = new LinkedList<>();
    public List> combinationSum(int[] candidates, int target) {
        dfs(candidates,target,0);
        return res;
    }
    private void dfs(int candidates[],int target,int cnt){
        if(target < 0)return;
        if(target == 0){
            res.add(new ArrayList(newList));
            return;
        }
        for(int i = cnt;i < candidates.length;i++){
            target -= candidates[i];
            newList.add(candidates[i]);
            dfs(candidates,target,i);
            target += candidates[i];
            newList.remove(newList.size() - 1);
        }
    }
}

时间复杂度O(n×2^{n})n为数组长度

空间复杂度O(target)最差情况下为targrt 

40 组合总和II

class Solution {
    List>res = new ArrayList<>();
    Listpath = new LinkedList<>();
    boolean st[];
    public List> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        st = new boolean[candidates.length];
        Arrays.fill(st,false);
        dfs(candidates,target,0);
        return res;
    }
    private void dfs(int candidates[],int target,int cnt){
        if(target < 0)return;
        if(target == 0){
            res.add(new LinkedList(path));
            return;
        }
        for(int i = cnt;i < candidates.length;i++){
            if(i > 0 && candidates[i] == candidates[i - 1] && !st[i - 1])continue;
            target -= candidates[i];
            path.add(candidates[i]);
            st[i] = true;
            dfs(candidates,target,i + 1);
            path.remove(path.size() - 1);
            st[i] = false;
            target += candidates[i];
        }
    }
}

时间复杂度O(n×2^{n})n为数组长度

空间复杂度O(n)最差情况下为n

131 分割回文串

class Solution {
    List>res = new ArrayList<>();
    Listpath = new LinkedList<>();
    public List> partition(String s) {
        dfs(s,0);
        return res;
    }
    private void dfs(String str,int start){
        if(start >= str.length()){
            res.add(new ArrayList(path));
            return;
        }
        for(int i = start;i < str.length();i++){
            if(judge(str,start,i)){
                String s = str.substring(start,i + 1);
                path.add(s);
                dfs(str,i + 1);
                path.remove(path.size() - 1);
            }else continue;
        }
    }
    private boolean judge(String str,int l,int r){
        while(r > l){
            if(str.charAt(l) != str.charAt(r))return false;
            l++;r--;
        }
        return true;
    }
}

时间复杂度O(n×2^{n})

空间复杂度O(n)

你可能感兴趣的:(代码随想录算法训练营,算法)