目次
Spring Bootでの実用的な機能をわかりやすく解説中
工作HardwareHubからのお知らせ
サンプルコード
#include <iostream>
#include <algorithm> // next_permutation のため。
using namespace std;
const int MAXN = 1024;
bool used[MAXN];
int perm[MAXN];
int perm2[MAXN];
// 表示用関数
void display(int* ptr, int n) {
for(int i = 0; i < n; ++i) {
cout << ptr[i] << " ";
}
cout << endl;
}
// 再帰関数による全探索 (深さ優先探索)
void permutation(int pos, int n) {
if(pos == n) {
display(perm, n);
return;
}
for(int i = 0; i < n; ++i) {
if(!used[i]) {
perm[pos] = i;
used[i] = true;
permutation(pos + 1, n);
used[i] = false;
}
}
}
// std::next_permutation による全探索 (順列の生成)
void permutation2(int n) {
for(int i = 0; i < n; ++i) {
perm2[i] = i;
}
do {
display(perm2, n);
} while(next_permutation(perm2, perm2 + n));
}
int main() {
permutation(0,3); cout << endl;
permutation2(3);
return 0;
}
出力例
$ g++ -Wall -O2 main.cpp && ./a.out
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
0
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- ダウンキャスト (C++をもう一度)実行時型情報 RTTI #include <iostream> #include <typeinfo> using namespace std; class MyClass { public: virtual ~MyClass() {} // typeid で正しい RTTI // (RunTime Type Information; 実行時型情報) ...
- 競技プログラミングの基本処理チートシート (C++)限られた時間の中で問題を解くために必要となる、競技プログラミングにおける基本的な処理のチートシートです。競プロにおけるメジャー言語 C++ を利用します。その際 C++11 の機能は利用せず C++03 の機能の範囲内で記述します。 頻度高く定期的に開催されるコンテスト AtCoder Codeforces main.cpp #include <iostream>
- 構造体と列挙体 (C++をもう一度)構造体 #include <iostream> using namespace std; struct MyStruct { char charval; int intval; }; void Show(MyStruct* obj) { cout << obj->intval << endl; } int main() { ...
- Valgrind による C/C++ メモリリーク検出JVM メモリリークでは JDK の jstat や jmap で原因を調査できます。C/C++ では valgrind の Memcheck ツールが利用できます。valgrind には複数のツールが含まれており既定のツールが Memcheck です。他のツールを利用する場合は --tool オプションで指定します。 [簡単な利用例](h
- クラスの基本/初期化 (C++をもう一度)構造体のように初期化する (非推奨) #include <iostream> using namespace std; const int MAX_STR = 16; class MyClass { public: int m_integer; char m_str[MAX_STR + 1]; void Show(); }; void MyClass::Show...