DAY23

组合总和

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

    }
    public void buildCombination(int[] candidates, int target,int sum,int index){
        if(sum>target)return;
        if(sum==target){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i=index;i<candidates.length;i++){
            path.add(candidates[i]);
            sum+=candidates[i];
            buildCombination(candidates,target,sum,i);
            path.removeLast();
            sum-=candidates[i];
        }
    }

组合总和 II

    List<List<Integer>> res=new ArrayList<List<Integer>>();
    LinkedList<Integer> path=new LinkedList<Integer>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        buildCombination(candidates,target,0,0);
        return res;


    }
    public void buildCombination(int[] candidates, int target,int sum,int index){
        
        if(sum==target){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i=index;i<candidates.length&&sum+candidates[i]<=target;i++){
            if(i>index&&candidates[i]==candidates[i-1]){
                continue;
            }
            sum+=candidates[i];
            path.add(candidates[i]);
            buildCombination(candidates,target,sum,i+1);
            sum-=candidates[i];
            path.removeLast();
        }
    }

分割回文串

    List<List<String>> res=new ArrayList<List<String>>();
    LinkedList<String> path=new LinkedList<String>();
    boolean[][]dp;
    public List<List<String>> partition(String s) {
        int len=s.length();
        dp=new boolean[len][len];
        computePalindrome(s);
        backtracking(s,0);
        return res;

    }
    public void backtracking(String s,int index){
        if(index>=s.length()){
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i=index;i<s.length();i++){
            if(dp[index][i]){
                path.add(s.substring(index,i+1));
                backtracking(s,i+1);
                path.removeLast();
            }

        }

    }
    public void computePalindrome(String s){
        char[]c= s.toCharArray();
        for(int i=s.length();i>=0;i--){
            for(int j=i;j<s.length();j++){
                if(c[i]==c[j]){
                    if(j-i<=1||dp[i+1][j-1])dp[i][j]=true;
                }
            }
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值