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);
        }
    }
  • 相关阅读:
    Oracle数据库的经典问题 snapshot too old是什么原因引起的
    在服务器上排除问题的头五分钟
    MySQL的redo log结构和SQL Server的log结构对比
    MySQL优化---DBA对MySQL优化的一些总结
    事务分类
    扩展HT for Web之HTML5表格组件的Renderer和Editor
    iOS平台快速发布HT for Web拓扑图应用
    HT for Web的HTML5树组件延迟加载技术实现
    Zip 压缩、解压技术在 HTML5 浏览器中的应用
    百度地图、ECharts整合HT for Web网络拓扑图应用
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9739247.html
Copyright © 2011-2022 走看看