算法學習十三----和爲n連續正數序列

題目:輸入一個正數n,輸出所有和爲n連續正數序列。
例如輸入15,由於1+2+3+4+5=4+5+6=7+8=15,所以輸出3個連續序列1-5、4-6和7-8。
算法思路
採用輔助空間保存序列。用i從1開始做起點,j從i+1開始,直到i等於(1+n)/2
1、如果i-j的和等於n,則輸出序列
2、如果i-j的和大於n,則將序列清空
3、如果i-j的和小於n,則將j假如到序列中

算法僞代碼:

void CotinuousSeq(int n)
     initialize a sequence

     for i <- 1 to (1+n)/2
          push first element

          for j <- i+1 to (1+n)/2
               if j+sum(tvec) <= n
                    then push into sequence

               if sum(ivec) = n
                    then print the sequence and clear the sequence
               else clear the sequence

C++實現

void CotinuousSeq(int n)
{
    //initialize a sequence
    vector<int> tvec;

    //for i <- 1 to (1+n)/2
    for(int i = 1; i <= (1+n)/2; ++i)
    {
        //push first element
        tvec.push_back(i);

        //for j <- i+1 to (1+n)/2
        for(int j = i+1; j <= (1+n)/2; ++j)
        {
            //if j+sum(tvec) <= n
            if((j + sum(tvec)) <= n)
            {
                //then push into sequence
                tvec.push_back(j);

                //if sum(ivec) = n
                if(sum(tvec) == n)
                {
                    //then print the sequence and clear the sequence
                    print(tvec);
                    tvec.clear();
                    break;
                }
            }
            else
            {
                //else clear the sequence
                tvec.clear();
                break;
            }
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章