持っているイテレータクラスを設計します。
- 文字列受け取るコンストラクタ
characters
ソートdistinctlowercase英文字と数字のcombinationLength
引数としてを。 - 機能 次の() 長さの次の組み合わせを返す
combinationLength
辞書式順序に。 - 関数 のhasNext() 戻りことを
True
次の組み合わせが存在する場合にのみ。
python3:itertools.combinationsを使用してモジュール
1 クラスCombinationIterator: 2 3 DEF __init__ (自己、A:STR、K:INT): 4 self.it = itertools.combinations(A、K) 5 self.last = A [ - K:] 6 self.res = " " 7 8 9 DEF次の(自己) - > STR: 10 self.res = '' .join(次(self.it)) 11 リターンself.res 12 13 DEFのhasNext(自己) - > BOOL: 14 戻り自己。 RES!= self.last
C ++:辞書順に沿って、部分文字列のすべての農産物の最初の。(バックトラック)
1 クラスCombinationIterator { 2 プライベート: 3 キュー< ストリング > イテレータ。 4 空隙 combinationIterator(CONST 文字列&文字、CONST INT&combinationLength、INT startpos、文字列&oneInstance、キュー< ストリング >&resultQueue){ 5 であれば(oneInstance.length()== combinationLength){ 6 resultQueue.push(oneInstance)。 7 リターン; 8 } 9 用(INT ; I <characters.length(); I = startpos ++ I){ 10 oneInstance.push_back(文字[I])。 11 combinationIterator(文字、combinationLength、I + 1 、oneInstance、resultQueue)。 12 oneInstance.pop_back()。 13 } 14 } 15 公共: 16 CombinationIterator(文字列文字、INT combinationLength){ 17 列 oneInstance = "" ; 18 combinationIterator(文字、combinationLength、0 、oneInstance、イテレータ)。 19 } 20 21 列(){次の 22 列 ANS = "" ; 23 であれば(のhasNext()){ 24 ANS = iterator.front()。 25 iterator.pop()。 26 } 27 リターンANS。 28 } 29 30 BOOL のhasNext(){ 31 // 队列非空、说明还有 32 リターン!iterator.empty(); 33 } 34 }。