2010年10月13日 星期三

窮舉例

'窮舉例
'以1,2,3三個數字, 可重覆方式組成7
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '最佳解
        Dim n = 7
        Dim a() = {3, 2, 1}
        Dim ansStr = ""
        Dim i = 0
        While n > 0
            While n >= a(i)
                n = n - a(i)
                ansStr = ansStr & a(i)
            End While
            i = i + 1
        End While
        MsgBox(ansStr)
        '所有解
        n = 7
        Dim k(a.Length - 1) As Integer
        For i = 0 To a.Length - 1
            k(i) = n \ a(i)
        Next
        Dim str1 = ""
        Dim str2 = ""
        Dim j1, j2, j3
        Dim z = 0
        For j3 = 0 To k(0)
            For j2 = 0 To k(1)
                For j1 = 0 To k(2)
                    If 3 * j3 + 2 * j2 + 1 * j1 = n Then
                        z = z + 1
                        str1 = "解" & z & " --> " & " 3:" & j3 & " 2:" & j2 & " 1:" & j1
                        str2 = str2 & str1 & vbTab
                        If z Mod 5 = 0 Then str2 = str2 & vbNewLine
                    End If
                Next
            Next
        Next
        MsgBox(str2)
        End
    End Sub
End Class

沒有留言: