码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode494

时间:2017-05-13 20:13:29      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:color   div   tar   var   dict   rip   for   http   esc   

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

标签:color   div   tar   var   dict   rip   for   http   esc   

原文地址:http://www.cnblogs.com/asenyang/p/6849908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!