我已经在网上搜索了几天了,但还没有找到满足我需求的好方法。所以我试着问。
我正在寻找一种方法,以产生所有可能的组合一个数字,而每个数字有不同的范围。
让我举一个例子:
我的输入: 1-3,0-9,4,2-3几个组合将是: 1042 1043 1142 1143 1242等等。
希望我说的很清楚..。
tnx
发布于 2011-05-27 12:09:08
您可以使用名为回溯的技术。
下面是C++中的一个例子。
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <cmath>
#include <complex>
#include <stack>
#include "time.h"
using namespace std;
template <typename T> string tostr(const T& t) { ostringstream os; os<<t; return os.str(); }
vector< pair< int, int > > ranges;
string cur;
void go(int at) {
if (at == (int)ranges.size()) {
// we're at the end of the ranges vector, print the number
cout<<cur<<endl;
return;
}
for(int i = ranges[at].first; i <= ranges[at].second; ++i) {
// add the digit for this range to the string
cur += tostr(i);
// recursive call
go(at+1);
// erase the last digit we added (this is where the backtracking part comes in)
cur.erase(cur.end()-1);
}
}
int main() {
ranges.push_back(make_pair(1,3));
ranges.push_back(make_pair(0,9));
ranges.push_back(make_pair(4,4));
ranges.push_back(make_pair(2,3));
cur = "";
go(0);
return 0;
}这是输出:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c C:\temp\temp2.exe
1042
1043
1142
1143
1242
1243
1342
1343
1442
1443
1542
1543
1642
1643
1742
1743
1842
1843
1942
1943
2042
2043
2142
2143
2242
2243
2342
2343
2442
2443
2542
2543
2642
2643
2742
2743
2842
2843
2942
2943
3042
3043
3142
3143
3242
3243
3342
3343
3442
3443
3542
3543
3642
3643
3742
3743
3842
3843
3942
3943
> Terminated with exit code 0.发布于 2017-11-15 01:20:52
尽管这是一个很老的问题,因为它被标记为C#,但没有C#答案,但这是我的变体。它是非递归的,这有助于在紧循环中实现性能:
var minimums = new[] { 2, 0, 1, 7, 1 };
var maximums = new[] { 4, 6, 3, 9, 4 };
var current = minimums.ToArray();
while (true)
{
Console.WriteLine(string.Join("", current));
int pos = 0;
while (pos < maximums.Length)
{
current[pos]++;
if (current[pos] <= maximums[pos])
break;
current[pos] = minimums[pos];
pos++;
}
if (pos == maximums.Length)
break;
}https://stackoverflow.com/questions/6151935
复制相似问题