zoukankan      html  css  js  c++  java
  • leetcode494

    You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
    Find out how many ways to assign symbols to make sum of integers equal to target S.
    Example 1:
    Input: nums is [1, 1, 1, 1, 1], S is 3.
    Output: 5
    Explanation:
    -1+1+1+1+1 = 3
    +1-1+1+1+1 = 3
    +1+1-1+1+1 = 3
    +1+1+1-1+1 = 3
    +1+1+1+1-1 = 3
    There are 5 ways to assign symbols to make the sum of nums be target 3.
    Note:
    1. The length of the given array is positive and will not exceed 20.
    2. The sum of elements in the given array will not exceed 1000.
    3. Your output answer is guaranteed to be fitted in a 32-bit integer.

    1.DFS。O(2^n)
    尝试所有+-的组合。

    2.DP


    本题有自带限制,就是最后的sum在1000内,其实就说明他们加减算出来的答案种类没有那么多。那如果你一直只用一个map,统计当前某一个数字有多少种方法算出来,那你遇到一个新数字的时候可以根据上一轮的map迭代出本轮的map。
    dp[i][j]表示从0~i-1的数字,拼出j有多少种拼法,最后的答案是dp[last][target]

    3.类DP的HashMap。
    相比Map节省空间,只记着当前确切出现过的sum对象。每次根据旧map得到新map的可能性。

    实现1 DFS:

    class Solution {
        public int findTargetSumWays(int[] nums, int S) {
            if (nums == null) {
                return 0;
            }
            return dfs(nums, 0, S, 0);
        }
        
        private int dfs(int[] nums, int crt, int target, int offset) {
            if (offset == nums.length) {
                return crt == target ? 1 : 0;
            }
            int ans = 0;
            ans += dfs(nums, crt + nums[offset], target, offset + 1);
            ans += dfs(nums, crt - nums[offset], target, offset + 1);
            return ans;
        }
    }

    实现3 HashMap:

    class Solution {
        public int findTargetSumWays(int[] nums, int S) {
            Map<Integer, Integer> count = new HashMap<>();
            count.put(0, 1);
            for (int num : nums) {
                Map<Integer, Integer> newCount = new HashMap<>();
                for (int sum : count.keySet()) {
                    newCount.put(sum + num, newCount.getOrDefault(sum + num, 0) + count.get(sum));
                    newCount.put(sum - num, newCount.getOrDefault(sum - num, 0) + count.get(sum));
                }
                count = newCount;
            }
            return count.getOrDefault(S, 0);
        }
    }
  • 相关阅读:
    RPC 在整个过程中,体现了逐层抽象,将复杂的协议编解码和数据传输封装到了一个函数中
    RPC 框架
    x86寄存器说明
    计算机组成原理—— 寻址方式--
    七种寻址方式(相对基址加变址寻址方式)---寄存器
    什么是寻址方式
    Intel寄存器名称解释及用途,%eax%ebx等都是什么意思
    CPU的内部架构和工作原理
    CPU工作流程
    8086内部寄存器
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9739247.html
Copyright © 2011-2022 走看看