Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) | A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver program to test above function
def findFourElements ( A , n , X ) : NEW_LINE INDENT for i in range ( 0 , n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if A [ i ] + A [ j ] + A [ k ] + A [ l ] == X : NEW_LINE INDENT print ( " % d , ▁ % d , ▁ % d , ▁ % d " % ( A [ i ] , A [ j ] , A [ k ] , A [ l ] ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT A = [ 10 , 2 , 3 , 4 , 5 , 9 , 7 , 8 ] NEW_LINE n = len ( A ) NEW_LINE X = 23 NEW_LINE findFourElements ( A , n , X ) NEW_LINE