n - 入力配列内の整数の数である反復を使用して、可能なすべての組み合わせ (n,k) を生成する C++ コードが必要です。k - 位置の数
たとえば、 入力:
n = [1 2 3];
k = 2;
出力:
A3 =
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
ありがとう。
n - 入力配列内の整数の数である反復を使用して、可能なすべての組み合わせ (n,k) を生成する C++ コードが必要です。k - 位置の数
たとえば、 入力:
n = [1 2 3];
k = 2;
出力:
A3 =
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
ありがとう。
標準ライブラリを使用する:
do {
for(int i = 0; i < k; i++){
std::cout << n[i];
}
std::cout << '\n';
} while (std::next_permutation(n, n + k));
これは基本的に基数 n-1 (すべての桁が 1 ずつシフトされる) でカウントされます。次のことを試してください。
編集:vector
の代わりにnew[]
使用delete[]
#include <vector>
void generatePerms(int n, int k)
{
vector<int> perms(k, 1);
//iterate through all permutations
bool done;
do {
//Do something with the current permutation, for example print it:
for (int i = 0; i < k-1; i++)
cout << perms[i] << ", ";
cout << perms[k-1] << endl;
/*
* Increment last digit first - if it's to big, reset to 1 and
* carry one (increment next digit), which may also carry one etc.
*
* If all digits caused a carry, then the permutation was n, n, ..., n,
* which means, that we can stop.
*/
done = true;
for (int i = k-1; i >= 0; i--) {
if (++perms[i] > n) {
perms[i] = 1;
continue;
} else {
done = false; //not all digits caused carry
break;
}
}
} while (!done);
}