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

leetcode300

时间:2018-10-04 20:25:43      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:cti   ict   max   remove   length   color   优先   solution   ||   

本题使用回溯法,深度优先搜索。使用隐式条件来进行加速。

public class Solution
    {
        int bestp = 0;
        int[] x;
        Dictionary<int, int> dic = new Dictionary<int, int>();

        void Backtrack(int[] nums, int t)
        {
            if (t >= nums.Length)
            {
                var sum = 0;
                for (int i = 0; i < nums.Length; i++)
                {
                    if (x[i] == 1)
                    {
                        //Console.Write(nums[i]+"   ");
                        sum++;
                    }                    
                }
                //Console.WriteLine();
                bestp = Math.Max(bestp, sum);
                return;
            }

            if (dic.Count == 0 || dic.LastOrDefault().Value < nums[t])
            {
                x[t] = 1;
                dic.Add(t, nums[t]);
                Backtrack(nums, t + 1);
                dic.Remove(t);
            }
            if (dic.Count + nums.Length - (t + 1) > bestp)
            {
                x[t] = 0;
                Backtrack(nums, t + 1);
            }
        }

        public int LengthOfLIS(int[] nums)
        {
            if (nums.Length < 2)
            {
                return nums.Length;
            }
            
            x = new int[nums.Length];
            Backtrack(nums, 0);

            return bestp;
        }
    }

 

leetcode300

标签:cti   ict   max   remove   length   color   优先   solution   ||   

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

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