LeetCode 494 Target Sum (hash 状压)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/88392150

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.

题目链接:https://leetcode.com/problems/target-sum/

题目分析:折半hash,状态压缩枚举

11ms,时间击败82.7%

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if (S > 1000 || S < -1000) {
            return 0;
        }
        int[] hash = new int[4005];
        int offset = 2000, cur, ans = 0;
        int n1 = (nums.length + 1) >> 1;
        int n2 = nums.length - n1;
        for (int sta = 0; sta < (1 << n1); sta++) {
            cur = 0;
            for (int i = 0; i < n1; i++) {
                cur += (sta & (1 << i)) == 0 ? nums[i] : -nums[i]; 
            }
            hash[offset + cur]++;
        }
        for (int sta = 0; sta < (1 << n2); sta++) {
            cur = 0;
            for (int i = 0; i < n2; i++) {
                cur += (sta & (1 << i)) == 0 ? nums[i + n1] : -nums[i + n1]; 
            }
            ans += hash[offset + S - cur];
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Tc_To_Top/article/details/88392150
今日推荐