首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成所有可能的数字组合,而每个数字都有不同的范围。

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

Stack Overflow用户
提问于 2011-05-27 11:58:19
回答 2查看 2.9K关注 0票数 1

我已经在网上搜索了几天了,但还没有找到满足我需求的好方法。所以我试着问。

我正在寻找一种方法,以产生所有可能的组合一个数字,而每个数字有不同的范围。

让我举一个例子:

我的输入: 1-3,0-9,4,2-3几个组合将是: 1042 1043 1142 1143 1242等等。

  1. 代码不能将所有的组合存储在内存中的某个变量中,因为我将处理大的数字(最多10位),程序可以用所有可能的方式制作txt文件,然后逐个编写它们,或者在控制台中打印它们。
  2. 输入数字长度和每个数字的范围在给定之前都是未知的。所以没有硬编码的嵌套循环。一定是动态的。

希望我说的很清楚..。

tnx

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-27 12:09:08

您可以使用名为回溯的技术。

下面是C++中的一个例子。

代码语言:javascript
复制
#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;
}

这是输出:

代码语言:javascript
复制
---------- 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.
票数 2
EN

Stack Overflow用户

发布于 2017-11-15 01:20:52

尽管这是一个很老的问题,因为它被标记为C#,但没有C#答案,但这是我的变体。它是非递归的,这有助于在紧循环中实现性能:

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6151935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档