首页 > 其他 > 详细

leetcode300

时间:2018-10-04 20:08:15      阅读:160      评论:0      收藏:0      [点我收藏+]

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!