首页 > 代码库 > leetcode494

leetcode494

public class Solution {
    public int FindTargetSumWays(int[] nums, int S) {
        Queue<int> Q = new Queue<int>();

            Q.Enqueue(0);

            var count = 0;
            var dic = new Dictionary<int, int>();
            var dic2 = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                var num = nums[i];
                dic2.Clear();
                foreach (var d in dic)
                {
                    dic2.Add(d.Key, d.Value);
                }
                dic.Clear();
                while (Q.Count > 0)
                {
                    var n = Q.Dequeue();
                    var N = 1;
                    if (dic2.ContainsKey(n))
                    {
                        N = dic2[n];
                    }

                    if (!dic.ContainsKey(n + num))
                    {
                        dic.Add(n + num, N);
                    }
                    else
                    {
                        dic[n + num] += N;
                    }

                    if (!dic.ContainsKey(n - num))
                    {
                        dic.Add(n - num, N);
                    }
                    else
                    {
                        dic[n - num] += N;
                    }
                }

                foreach (var l in dic.Keys)
                {
                    if (l == S && i == nums.Length - 1)
                    {
                        count = dic[l];
                    }
                    else
                    {
                        Q.Enqueue(l);
                    }
                }
            }
            return count;
    }
}

https://leetcode.com/problems/target-sum/#/description

leetcode494