在我遇到的众多算法题中,有些题目如果用常规的排序或搜索算法,很难达到最优的时间或空间复杂度。那么此时,可以换一种角度,直接生成法可以避免排序、暴力搜索。
1. 生成丑数
long long kthPrimeNumber(int k)
{
vector<long long> uglyData(k+1);
uglyData[0] = 1;
int index3 = 0;
int index5 = 0;
int index7 = 0;
int currentIndex = 1;
while(currentIndex <= k)
{
long long temp = min(uglyData[index3] * 3, uglyData[index5] * 5);
uglyData[currentIndex] = min(temp, uglyData[index7] * 7);
while(uglyData[index3]*3 <= uglyData[currentIndex])
index3++;
while(uglyData[index5]*5 <= uglyData[currentIndex])
index5++;
while(uglyData[index7]*7 <= uglyData[currentIndex])
index7++;
currentIndex++;
}
return uglyData[k];
}
2.对1到n的连续自然数进行字典顺序的排列
/*************************************************************************
> File Name: DictionarySort.cpp
> Author: Shaojie Kang
> Mail: kangshaojie@ict.ac.cn
> Created Time: 2015年09月10日 星期四 16时17分48秒
> Problem:
给定一个数n,求1到n的字典顺序排列
************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
void GenerateSequenceCore(int n, int currentNum, vector<int> &result)
{
for(int i = 0; i <= 9; ++i)
{
int temp = currentNum * 10 + i;
if(temp == 0) continue;
if(temp <= n)
{
result.push_back(temp);
GenerateSequenceCore(n, temp, result);
}
else break;
}
}
vector<int> GenerateSequence(int n)
{
vector<int> result;
GenerateSequenceCore(n, 0, result);
for(int i = 0; i < result.size(); ++i)
cout<<result[i]<<" ";
cout<<endl;
return result;
}
int main()
{
vector<int> result = GenerateSequence(30);
return 0;
}
3.给定一个正整数M,求最小的N,使得N*M只含有0和1
int GenerateNum01_2(int N)
{
vector<vector<int> >bigInt(N);
bigInt[1].push_back(0);
int noUpdates = 0;
for(int i = 1, j = 10%N; ; ++i, j = (j*10)%N)
{
bool flag = false;
if(0 == bigInt[j].size())
{
flag = true;
bigInt[j].push_back(i);
}
for(int k = 1; k < N; ++k)
{
if(bigInt[k].size() > 0 && i > bigInt[k][bigInt[k].size() - 1] && bigInt[(k+j)%N].size() == 0)
{
flag = true;
int index = (k + j) % N;
bigInt[index].insert(bigInt[index].begin(), bigInt[k].begin(), bigInt[k].end());
bigInt[index].push_back(i);
}
}
if(flag == false) noUpdates++;
else noUpdates = 0;
if(noUpdates == N || bigInt[0].size() > 0)
break;
}
if(noUpdates == N) return -1;
int result = 0;
for(int i = 0; i < bigInt[0].size(); ++i)
{
result += (int)pow(10 , bigInt[0][i]);
}
return result;
}