给定一个长度为N的数组,找出一个最长的单调自增子序列(不一定连续,但是顺序不能乱). 第二解

来源:互联网 发布:阿里云域名管理在哪 编辑:程序博客网 时间:2024/06/05 15:12
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    public class Program    {        private static int length = 4;        private int[] arr = { 1,5,4,8};        //这个数组代表这一位能取到的最大长度是多少        private int[] key = new int[length];        public static void Main(String[] args)        {            new Program().run();        }        private void run()        {            key[0] = 0;            int max = 1;            for (int i = 1; i < length; i++)            {                int temp = 0;                for (int j = i - 1; j >= 0; j--)                {                    //找出比该位小的数                    if (arr[i] > arr[j])                    {                        //temp表示该为能取到的最大长度 遍历i前面的所有j取 key[j]值最大的一个,如果前面有key[i]的但是比temp小保持原状                        temp = temp < key[j] + 1 ? key[j] + 1 : temp;                    }                }                //记录i点取的最大长度。                key[i] = temp;                //max代表最大长度.                 if (max <= temp)                {                    max++;                }            }            Console.WriteLine("max lenght:" + max); ;            for (int i = length - 1; i >= 0; i--)            {                //如果这个值逆着输出可以取到对应的最大长度则输出。                if (key[i] == max - 1)                {                    Console.WriteLine(arr[i] + " ");                    max--;                }            }            Console.Read();        }    }}


结果如图
2 0
原创粉丝点击