File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Permutation implements java .util .Iterator <int []> {
2+ private int [] next ;
3+
4+ public Permutation (int n ) {
5+ next = java .util .stream .IntStream .range (0 , n ).toArray ();
6+ }
7+
8+ @ Override
9+ public boolean hasNext () {
10+ return next != null ;
11+ }
12+
13+ @ Override
14+ public int [] next () {
15+ int [] r = next .clone ();
16+ next = nextPermutation (next );
17+ return r ;
18+ }
19+
20+ public static int [] nextPermutation (int [] a ) {
21+ if (a == null || a .length < 2 )
22+ return null ;
23+ int p = 0 ;
24+ for (int i = a .length - 2 ; i >= 0 ; i --) {
25+ if (a [i ] >= a [i + 1 ])
26+ continue ;
27+ p = i ;
28+ break ;
29+ }
30+ int q = 0 ;
31+ for (int i = a .length - 1 ; i > p ; i --) {
32+ if (a [i ] <= a [p ])
33+ continue ;
34+ q = i ;
35+ break ;
36+ }
37+ if (p == 0 && q == 0 )
38+ return null ;
39+ int temp = a [p ];
40+ a [p ] = a [q ];
41+ a [q ] = temp ;
42+ int l = p , r = a .length ;
43+ while (++l < --r ) {
44+ temp = a [l ];
45+ a [l ] = a [r ];
46+ a [r ] = temp ;
47+ }
48+ return a ;
49+ }
50+ }
Original file line number Diff line number Diff line change 1+ # クラス Permutation
2+
3+ 本機能は AtCoderLibrary ではなく C++標準ライブラリ ` std::next_permutation ` の移植です.
4+
5+ $N$が与えられたとき,長さ$N$の順列を辞書順に列挙することができます.
6+
7+ ## コンストラクタ
8+
9+ ### Permutation
10+
11+ ``` java
12+ public Permutation(int n)
13+ ```
14+
15+ 長さ$N$の順列を列挙するイテレータを作ります. 計算量 $O(N)$
16+
17+ ## メソッド
18+
19+ ### hasNext
20+
21+ ``` java
22+ public boolean hasNext()
23+ ```
24+
25+ イテレータが後続の要素を保持する場合に真を返します.計算量 $O(1)$
26+
27+ ### next
28+
29+ ``` java
30+ public int [] next()
31+ ```
32+
33+ イテレータの後続の要素を取得します.計算量 $O(N)$
34+
35+ ### nextPermutation
36+
37+ ``` java
38+ public static int [] nextPermutation(int [] a)
39+ ```
40+
41+ 与えられた順列に対して,辞書順でその直後となるような順列を返却します.
42+ 但し,入力の配列が辞書順最大の場合は` null ` を返却します.
43+ 入力配列中の任意の 2 要素が相異なることを仮定しています.
44+ また,入力で与えられた順列を破壊的に変更することに注意してください.
45+ 計算量 $O(N)$
You can’t perform that action at this time.
0 commit comments