Skip to content

Commit 4d46a8e

Browse files
authored
feat: add next_permutations_with_reps snippets
1 parent b5c7eaa commit 4d46a8e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// N = len of v
2+
// O(N^(r - l + 1) * N)
3+
bool next_permutations_with_reps(vector<int> &v, int l, int r) {
4+
assert(l < r && !v.empty());
5+
if (all_of(v.begin(), v.end(), [&](int x) { return x == r; }))
6+
return false;
7+
8+
for (int i = int(v.size()) - 1; i >= 0; --i) {
9+
if (v[i] == r) {
10+
v[i] = l;
11+
} else {
12+
++v[i];
13+
return true;
14+
}
15+
}
16+
return false;
17+
}
18+
// Usage:
19+
// int n = 3, l = 1, r = 3, cnt = 1;
20+
// vector<int> v(n, l);
21+
// do {
22+
// cout << cnt++ << ") ";
23+
// for (auto &x : v) {
24+
// cout << x << ' ';
25+
// }
26+
// cout << '\n';
27+
// } while (next_permutations_with_reps(v, l, r));
28+
29+
// Sample:
30+
// n=3, l=1, r=3
31+
// {1, 2, 3} * {1, 2, 3} * {1, 2, 3} = 3 * 3 * 3 = 27
32+
// 1) 1 1 1
33+
// 2) 1 1 2
34+
// 3) 1 1 3
35+
// 4) 1 2 1
36+
// 5) 1 2 2
37+
// 6) 1 2 3
38+
// 7) 1 3 1
39+
// 8) 1 3 2
40+
// 9) 1 3 3
41+
// 10) 2 1 1
42+
// 11) 2 1 2
43+
// 12) 2 1 3
44+
// 13) 2 2 1
45+
// 14) 2 2 2
46+
// 15) 2 2 3
47+
// 16) 2 3 1
48+
// 17) 2 3 2
49+
// 18) 2 3 3
50+
// 19) 3 1 1
51+
// 20) 3 1 2
52+
// 21) 3 1 3
53+
// 22) 3 2 1
54+
// 23) 3 2 2
55+
// 24) 3 2 3
56+
// 25) 3 3 1
57+
// 26) 3 3 2
58+
// 27) 3 3 3

0 commit comments

Comments
 (0)