C++ Algorithm: Pick n numbers from 2D Matrix based on certain conditions
===

I have a 2D matrix of size [3][x] filled with numbers. I want to pick say x numbers from this matrix based on the condition 

1) exactly one number from each column.

2) upto a Max of 'm' numbers from each row(total of all the 3 rows should be x numbers and 3m > x)

I want to find the least possible sum of these selected x numbers.

I was able to pick the numbers based on iterative approach of finding the 'x' small numbers based on above conditions from the matrix. But my answer is not optimal.
Eg: 

        5 9 . . . . 
        6 15 . . . .
        7 19 . . . .
Lets say 5 is picked up initially(so 6 and 7 cannot be picked now). Later on we try to pick 9 but if m elements of row(0) are over we will have to pick 15. Now our solution will be 5+15 = 20 but we could have used 6+9 = 15 as optimal solution. 


I am trying to optimize my solution and looking for better algorithms. Can someone provide me some good idea for optimal solution?

Thanks 
