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

leetcode39

时间:2018-10-08 19:33:39      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:etc   bre   new   backtrac   solution   tco   pos   leetcode   sam   

public class Solution
    {
        List<IList<int>> list = new List<IList<int>>();//全部记录
        List<int> records = new List<int>();//一条记录        
        bool bk = false;
        private void BackTrack(List<int> candidates, int target, int sum)
        {
            if (sum == target)
            {
                int[] temp = new int[records.Count];
                records.CopyTo(temp);
                bool same = false;
                foreach (var l in list)
                {
                    if (l.Count == temp.Length)
                    {
                        var l1 = l.OrderBy(x => x).ToList();
                        var l2 = temp.OrderBy(x => x).ToList();
                        var samecount = 0;
                        for (int x = 0; x < l1.Count; x++)
                        {
                            if (l1[x] == l2[x])
                            {
                                samecount++;
                            }
                        }
                        if (samecount == l.Count)
                        {
                            same = true;
                            break;
                        }
                    }                    
                }
                if (!same)
                {
                    list.Add(temp.ToList());
                }
                bk = true;
                return;
            }
            else if (sum < target)
            {
                bk = true;
                for (int position = 0; position < candidates.Count; position++)
                {
                    var cur = candidates[position];
                    sum += cur;
                    records.Add(cur);
                    BackTrack(candidates, target, sum);
                    //回溯
                    records.RemoveAt(records.Count - 1);
                    sum -= cur;
                    if (bk)
                    {
                        bk = false;
                        break;
                    }
                }
            }
            else
            {
                bk = true;
                return;
            }
        }

        public IList<IList<int>> CombinationSum(int[] candidates, int target)
        {
            var can = candidates.OrderBy(x => x).ToList();
            BackTrack(can, target, 0);
            return list;
        }
    }

 

leetcode39

标签:etc   bre   new   backtrac   solution   tco   pos   leetcode   sam   

原文地址:https://www.cnblogs.com/asenyang/p/9756126.html

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