Find valid assignments of integers in arrays (permutations with given order)

前端 未结 5 1386
醉梦人生
醉梦人生 2021-01-06 06:33

I am having a general problem finding a good algorithm for generating each possible assignment for some integers in different arrays.

Lets say I have n arrays and m

5条回答
  •  借酒劲吻你
    2021-01-06 07:12

    This will be easy with backtracking recursion. You should track which array you are filling and which number you are up to. Something like that:

    void gen(int arrayN, int number)
    {
       if (number == MAX_NUMBER + 1) //We have a solution
       {
            printSolution();
            return;
       }
    
       if (arrayN == MAX_ARRAYS + 1) //No solution
           return;
    
       gen(arrayN + 1, number); //Skip to next array
    
       for (int i = number; i <= MAX_NUMBER; i++)
       {
           //Save at this line the numbers into an array for the solution
           gen(arrayN + 1, i + 1); //Used the numbers from "number" to "i" inclusive
       }
    }
    
    gen(0, 1);
    

提交回复
热议问题