四、算法_动态规划

来源:互联网 发布:宋松淘宝模特 编辑:程序博客网 时间:2024/05/20 05:07

动态规划

  1. 自顶向下递归
  2. 自底向上

动态规划与分治法类似

自顶向下递归C#实现:

 //  自顶向下递归 - 钢条切割    class Program {        static void Main (string[] args) {            //  出售长度            int n = 5;            int[] pPrices = new[] { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };            Console.WriteLine(BuyUpDown(0,pPrices));            Console.WriteLine(BuyUpDown(5, pPrices));            Console.ReadKey();        }        public static int BuyUpDown (int n, int[] pPrices) {            if (n == 0) {                return 0;            }            int pTempMaxPrice = 0;            for (int i = 1; i < n + 1; i++) {                int pMaxPrices = pPrices[i] + BuyUpDown(n - i, pPrices);                if (pMaxPrices > pTempMaxPrice) {                    pTempMaxPrice = pMaxPrices;                }            }            return pTempMaxPrice;        }    }

缺点:性能低,效率低。

动态规划(带备忘)的自顶向下的实现:

对计算的结果进行保存,避免进行二次运算,但是要付出空间带价。

class Program {        static void Main (string[] args) {            //  出售长度            //int n = 5;            int[] pPrices = new[] { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };            int[] pResult = new int[pPrices.Length+1];            Console.WriteLine(BuyUpDown(0, pPrices, pResult));            Console.WriteLine(BuyUpDown(5, pPrices, pResult));            Console.ReadKey();        }        public static int BuyUpDown (int n, int[] pPrices, int[] pResult) {            if (n == 0) {                return 0;            }            if (pResult[n] != 0) {                return pResult[n];            }            int pTempMaxPrice = 0;            for (int i = 1; i < n + 1; i++) {                int pMaxPrices = pPrices[i] + BuyUpDown(n - i, pPrices, pResult);                if (pMaxPrices > pTempMaxPrice) {                    pTempMaxPrice = pMaxPrices;                }            }            pResult[n] = pTempMaxPrice;            return pTempMaxPrice;        }    }

自底向上:小问题依次解决大问题。

class Program {        static void Main (string[] args) {            //  出售长度            int[] pPrices = new[] { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };            int[] pResult = new int[pPrices.Length + 1];            Console.WriteLine(BottomUp(0,pPrices,pResult));            Console.WriteLine(BottomUp(1, pPrices, pResult));            Console.ReadKey();        }        public static int BottomUp (int n, int[] pPrices, int[] pResult) {            for (int i = 1; i < n + 1; i++) {                //  取得长度为 i 的最大收益                int pTempMaxPrices = -1;                for (int j = 1; j <= i; j++) {                    int pMaxPrices = pPrices[j] + pResult[i - j];                    if (pMaxPrices > pTempMaxPrices)                    {                        pTempMaxPrices = pMaxPrices;                    }                }//End for j                pResult[i] = pTempMaxPrices;            }//End for i            return pResult[n];        }// End BottomUp    }
0 0