力扣Hot100每日N题(15~28)

124. 二叉树中的最大路径和

class Solution {
    int ans = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        dfs(root);
        return ans;
    }
    public int dfs(TreeNode root){
        if(root == null) return 0;
        int l = Math.max(0, dfs(root.left));
        int r = Math.max(0, dfs(root.right));
        ans = Math.max(ans, l + r + root.val);
        return Math.max(l, r) + root.val;
    }
}

322. 零钱兑换

class Solution {
    int[] dp;
    public int coinChange(int[] coins, int amount) {
        dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        // coins = Arrays.stream(coins)
        //     .boxed()
        //     .sorted((a, b) -> b - a)
        //     .mapToInt(Integer::intValue)
        //     .toArray();
        System.out.println(Arrays.toString(coins));
        dp[0] = 0;
        for(int i = 0; i <= amount; i++){
            for(int coin : coins){
                if(coin <= amount - i) 
                    dp[coin + i] = Math.min(dp[coin + i], dp[i] + 1);
            }
        }
        return dp[amount] == amount + 1 ? -1 : dp[amount];
    }
}

494. 目标和

class Solution {
    int ans = 0;
    void dfs(int[] nums, int idx, int res, int target){
        if(idx == nums.length){
            if(res == target) ans++;
            return ;
        }
        dfs(nums, idx + 1, res + nums[idx], target);
        dfs(nums, idx + 1, res - nums[idx], target);
    }
    public int findTargetSumWays(int[] nums, int target) {
        dfs(nums, 0 , 0, target);
        return ans;
    }
}

461. 汉明距离

class Solution {
    public int hammingDistance(int x, int y) {
        int z = x ^ y, ans = 0;
        while(z > 0){
            ans += z & 1;
            z >>= 1;
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值