平均分割一個數組


最近想平均分割一個數組,比如把一個10數的數組分成6個數組的,最好的分法是2,2,2,2,1,1,這個2很好求出,直接10/6上取整就可以了,但是如果按2去分割的話,最后會變成2,2,2,2,2,0這樣不均勻的分法,很是蛋疼。

 

今天休息,想了一下這個問題,發現可以用遞歸來解決。比如先分出2來,遞歸將8分成5個數組,有能分出2來,遞歸將6分成4個數組,在分出2來,變成了遞歸將4分成3個數組,又可以分出2來,那就變成了將2分成2個數組,下一步就很明顯了。

 

不多說了,直接上碼,希望對遇到同問題的人有所幫助,這也算我的功德了。


View Code
#include <iostream>
#include <vector>

using  namespace std;

template <typename T>
vector<vector<T> > average_divide(T ar[],  int size,  int cnt)
{
    vector<vector<T> > res;
     if (cnt ==  0)
    {
         return res;
    }

    vector<T> first;
     int first_size = (size -  1) / cnt +  1;
     for ( int i =  0; i < first_size; i++)
    {
        first.push_back(ar[i]);
    }
    res.push_back(first);
    vector<vector<T> > other = average_divide(ar + first_size, size - first_size, cnt -  1);
     for (vector<vector<T> >::iterator it = other.begin(); it != other.end(); it++)
    {
        res.push_back(*it);
    }
     return res;
}

int main()
{
     int a[] = { 1457698032};
    vector<vector< int> > res = average_divide(a,  106);
     for (vector<vector< int> >::iterator it = res.begin(); it != res.end(); it++)
    {
         for (vector< int>::iterator vit = it->begin(); vit != it->end(); vit++)
        {
            cout << *vit <<  '   ';
        }
        cout << endl;
    }
     return  0;
}
下載地址: AverageDivide.cpp


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM