@@ -9,49 +9,31 @@ namespace Advanced.Algorithms.Combinatorics
99 public class Variation
1010 {
1111 /*Variations are arrangements of selections of objects, where the order of the selected objects matters.
12- To count k -element variations of n objects, we first need to choose a k -element combination and then
12+ To count r -element variations of n objects, we first need to choose a r -element combination and then
1313 a permutation of the selected objects*/
1414
1515 //Without repetition
16- /* It is also the number of ways of putting r distinct balls into input.Count distinct boxes such that each box
16+ /* It is also the number of ways of putting n distinct balls into r distinct boxes such that each box
1717 receives at most one element. */
1818
1919 //With repetition
20- /* It is the number of all ways of putting r distinct balls into input.Count distinct boxes */
20+ /* It is the number of all ways of putting n distinct balls into r distinct boxes */
2121 public static List < List < T > > Find < T > ( List < T > input , int r , bool withRepetition )
2222 {
23- var result = new List < List < T > > ( ) ;
23+ var combinations = new List < List < T > > ( ) ;
2424
25- Recurse ( input , r , withRepetition , new List < T > ( ) , new HashSet < int > ( ) , result ) ;
25+ combinations . AddRange ( Combination . Find ( input , r , withRepetition ) ) ;
2626
27- return result ;
28- }
27+ var variations = new List < List < T > > ( ) ;
2928
30- private static void Recurse < T > ( List < T > input , int r , bool withRepetition ,
31- List < T > prefix , HashSet < int > prefixIndices ,
32- List < List < T > > result )
33- {
34- if ( prefix . Count == r )
29+ foreach ( var combination in combinations )
3530 {
36- result . Add ( new List < T > ( prefix ) ) ;
37- return ;
31+ variations . AddRange ( Permutation . Find ( combination , combination . Count ) ) ;
3832 }
3933
40- for ( int j = 0 ; j < input . Count ; j ++ )
41- {
42- if ( prefixIndices . Contains ( j ) && ! withRepetition )
43- {
44- continue ;
45- }
46-
47- prefix . Add ( input [ j ] ) ;
48- prefixIndices . Add ( j ) ;
49-
50- Recurse ( input , r , withRepetition , prefix , prefixIndices , result ) ;
51-
52- prefix . RemoveAt ( prefix . Count - 1 ) ;
53- prefixIndices . Remove ( j ) ;
54- }
34+ return variations ;
5535 }
36+
37+
5638 }
5739}
0 commit comments