이 문제에서는 두 개의 정수 값 k 및 n이 제공됩니다. 그리고 우리는 1에서 n까지의 숫자에서 길이가 k인 모든 시퀀스를 정렬된 순서로 인쇄해야 합니다.
주제를 이해하기 위해 예를 들어 보겠습니다 -
Input:k = 2 ; n = 3 Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
따라서 이 문제에서는 위에서 설명한 순서대로 인쇄해야 합니다.
이 문제를 해결하는 간단한 방법은 시퀀스의 정수를 최대값, 즉 n에 도달할 때까지 증가시키는 것입니다. 다음은 솔루션에 대한 자세한 설명입니다.
알고리즘
1) Create an array of size k with all values = 1 i.e. {1, 1, ..ktimes}.
2) Repeat step 3 and 4 till the array becomes {n, n, …, n}.
3) Print the array.
4) Increment the value such that the elements of the array become the next value. For example, {1, 1, 1} incremented to {1, 1, 2} and {1, 3, 3} incremented to {2, 1, 1}. For this we need to check the kth element of the array, if it’s equal to n become update, then check k-1 element in the sequence and so on for the same condition. 예시
다음 프로그램을 통해 개념을 보다 명확하게 이해할 수 있습니다.
#include<iostream>
using namespace std;
void printSequence(int arr[], int size){
for(int i = 0; i < size; i++)
cout<<arr[i]<<"\t";
cout<<endl;
return;
}
int nextElement(int arr[], int k, int n){
int s = k - 1;
while (arr[s] == n)
s--;
if (s < 0)
return 0;
arr[s] = arr[s] + 1;
for(int i = s + 1; i < k; i++)
arr[i] = 1;
return 1;
}
void generateSequence(int n, int k){
int *arr = new int[k];
for(int i = 0; i < k; i++)
arr[i] = 1;
while(1){
printSequence(arr, k);
if(nextElement(arr, k, n) == 0)
break;
}
return;
}
int main(){
int n = 3;
int k = 2;
cout<<"The sequence is :\n";
generateSequence(n, k);
return 0;
} 출력
순서는 -
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
이 방법은 이해하기 쉽지만 더 좋고 효율적으로 만들 수 있습니다.
이 방법은 재귀와 추가 인덱스를 사용하여 시퀀스 오프셋(그 이후에 시퀀스가 뒤집힐 값)을 확인합니다. 이 함수는 재귀적으로 호출되며 인덱스까지 용어를 업데이트하지 않습니다. 그리고 인덱스 이후의 다음 항에 대한 함수를 재귀화합니다.
예시
#include<iostream>
using namespace std;
void printSequence (int arr[], int size){
for (int i = 0; i < size; i++)
cout << arr[i] << "\t";
cout << endl;
return;
}
void generateSequence (int arr[], int n, int k, int index){
int i;
if (k == 0){
printSequence (arr, index);
}
if (k > 0){
for (i = 1; i <= n; ++i){
arr[index] = i;
generateSequence (arr, n, k - 1, index + 1);
}
}
}
int main (){
int n = 3;
int k = 2;
int *arr = new int[k];
cout<<"The sequence is:\n";
generateSequence (arr, n, k, 0);
return 0;
} 출력
순서는 -
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3