zoukankan      html  css  js  c++  java
  • 和为S的连续正数数列,动态规划,C++

    一个简单的思考方式是5+6+7+8的和可以看成(5+6+7)+8,所以就可以想到动态规划的方法

    设一个二维数组,i代表数列长度为(i+1),j代表数列首部数字。

    比如说求和为5的连续正数数列

    class Solution {
    public:
        vector<vector<int> > FindContinuousSequence(int sum) {
            vector<vector<int> > ret;
            int** array = new int*[sum - 1];
            for (int i = 0; i < sum - 1; i++)
            {
                array[i] = new int[sum - 1];
            }
            for (int i = 0; i < sum -1; i++)
            {
                array[0][i] = i + 1;
            }
            for (int i = 1; i < sum - 1; i++)
            {
                for (int j = 0; j < sum - 2; j++)
                {
                    array[i][j] = array[i -1][j] + array[0][j + i];
                    if (array[i][j] > sum)
                    {
                        break;
                    }
                    if (array[i][j] == sum)
                    {
                        vector<int> vec;
                        vec.reserve(i + 1);
                        for (int k = j + 1;k <= i + j + 1;k++)
                        {
                            vec.push_back(k);
                        }
                        ret.push_back(vec);
                    }
                }
            }
            vector<vector<int> >realRet;
            realRet.reserve(ret.size());
            for (int i = ret.size() - 1; i >= 0; i--)
            {
               realRet.push_back(ret[i]); 
            }
            return realRet;
        }
    };
  • 相关阅读:
    Run Shell Commands in Python
    Install Fabric 1.8.3 Manually on Ubuntu 12.04
    Setup a Simple HTTP Proxy Server
    去掉文件中的^M
    Build Web Server with Apache and Passenger
    Delete Trailing Spaces with Vim
    Specify Default JDK on Ubuntu
    总结
    问题
    HTTPS 和 HTTP
  • 原文地址:https://www.cnblogs.com/adamhome/p/7955637.html
Copyright © 2011-2022 走看看