參與的Pb算法:5個數的排列組合。

原貼 地址:http://community.csdn.net/Expert/TopicView3.asp?id=5338869

題如下:用1、2、2、3、4、5這六個數字,用pb寫一個函數,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"與"5"不能相連.

我的算法:



Char lc_point[6] = {'1','2','2','3','4','5'}
Char lc_temp
Int  i,j,k,l
String ls_points[]
//l = 0
Do
    If lc_point[3] = '4' Or Pos(lc_point,"35") > 0 Or Pos(lc_point,"53") > 0 Then
    Else
        l ++
        ls_points[l] = lc_point       
        //dw_1.Object.#1[dw_1.InsertRow(0)] = lc_point
    End If
    //下一個
    For i = 5 To 1 Step -1
        If lc_point[i] < lc_point[i + 1] Then Exit
    Next
    //
    j = 6 - i
    If i > 0 Then
        //lc_point = Left(lc_point,i) + Reverse(Right(lc_point,j))   
        //下面的Choose語句是上面的變體,爲了速度
        Choose Case j
            Case 1
                lc_temp = lc_point[6]
                lc_point[6] = lc_point[5]
                lc_point[5] = lc_temp
            Case 2
                lc_temp = lc_point[6]
                If lc_temp > lc_point[4] Then
                    lc_point[6] = lc_point[5]
                    lc_point[5] = lc_point[4]
                    lc_point[4] = lc_temp                   
                Else       
                    lc_point[6] = lc_point[4]
                    lc_point[4] = lc_point[5]                       
                    lc_point[5] = lc_temp
                End If               
            Case Else                           
                k = i + 1
                j = 6
                do
                    lc_temp = lc_point[j]
                    lc_point[j] = lc_point[k]
                    lc_point[k] = lc_temp
                    k ++
                    j --
                Loop While k < j
                //如果搞個二分查找,可能會快些
                lc_temp = lc_point[i]
                For k = i + 1 To 6
                    If lc_point[k] > lc_temp Then
                        lc_point[i] = lc_point[k]
                        lc_point[k] = lc_temp
                        Exit
                    End If
                Next
        End Choose
    Else
        Exit
    End If   
Loop While True

i = dw_1.RowCount() + 1
//If i = 0 Then i = 1
dw_1.Object.#1[i,i + l - 1] = ls_points


思路:由於是由字符組成的字符串,字符是固定的,所以我使用了 首先把字符排序(從小到大),然後遞增(把大的數排到前面去,小的數挪到後面去,同時保證爲遞增的方式),最後爲從大到小,這樣我們就達到了組合的目的了。然後對特殊的幾種組和進行判斷就好。


發現把  一個數組中的數據填入DW一列用dw_1.OBject.#1.Current或者我上面的,真快。幾乎不佔用多少時間。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章