generating Variations without repetitions / Permutations in java

后端 未结 10 961
半阙折子戏
半阙折子戏 2021-01-02 07:33

I have to generate all variations without repetitions made of digits 0 - 9.

Length of them could be from 1 to 10. I really don\'t know how to solve it, especially ho

10条回答
  •  时光说笑
    2021-01-02 07:46

    The code for this is similar to the one without duplicates, with the addition of an if-else statement.Check this code

    In the above code,Edit the for loop as follows

    for (j = i; j <= n; j++)
    {
    
    if(a[i]!=a[j] && !is_duplicate(a,i,j))              
        {
            swap((a+i), (a+j));
            permute(a, i+1, n);
            swap((a+i), (a+j)); 
        }
        else if(i!=j)  {}  // if no duplicate is present , do nothing           
        else permute(a,i+1,n);  // skip the ith character
    }
    
    bool is_duplicate(int *a,int i,int j) 
    {
         if a[i] is present between a[j]...a[i] 
            return 1;
        otherwise
            return 0;
    
    }
    

    worked for me

提交回复
热议问题