生成数字的所有可能组合,而每个数字的范围都不相同

|| 我已经在互联网上搜索了几天,但没有找到满足我需求的好方法。病了,试着问。 我正在寻找一种方法来生成数字的所有可能组合,而每个数字都具有不同的范围。 让我给你举个例子: 我的输入:[1-3],[0-9],[4],[2-3] 几种组合将是: 1042 1043 1142 1143 1242 等等... 该代码不得将所有组合都存储在内存中的某个变量中,因为我将使用大数字(最多10位数字),该程序可以制作具有所有可能的txt文件,然后一一写入或仅打印出来他们在控制台。 输入数字的长度和每个数字的范围直到给出之前都是未知的。因此没有硬编码的嵌套循环。它必须是动态的。 我希望我很清楚。 n     
已邀请:
        您可以使用一种称为回溯的技术。 这是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.
    
        即使这是一个非常古老的问题,看到它的标签为
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;
}
    

要回复问题请先登录注册