[英]How to get all possible n-digit numbers that can be formed using given digits?
[英]Algorithm to generate all possible N-digit numbers with whose digits are in increasing order
我想要一個算法來生成所有可能的N位數字,其數字按遞增順序排列。
例如:如果N = 3,那么可能的數字是:012,123,234,246,567,259,因為:
0 <1 <2
...
2 <5 <9
等等
我該怎么做?
我開發了以下算法,但它只生成連續增加數字的數字,如123,234,345,456,567等。因此,錯過了一大組數字。
private static void generate(int start,int n)
{
if((start+n)>9)
return;
else
{
for(int i=0;i<n;i++)
System.out.print(start+i);
System.out.println();
generate(start+1,n);
}
}
試着保留你原來的想法:
private static void generate(int prefix, int start, int n)
{
if (n == 0)
{
System.out.print(prefix);
System.out.println();
}
else
{
for(int i=start;i<10;i++)
generate(10*prefix+i, i+1, n-1);
}
}
從更具說明性的角度來看,算法看起來幾乎就像數學符號(在Haskell中):
generate = toInt [[a,b,c] | a <- x, b <- x, c <- x, a < b, b < c]
where x = [0..9]
toInt = map (foldl (\n m -> 10*n + m) 0)
其中map (foldl (\\nm -> 10*n + m) 0)
只是將一個數字列表轉換為一個整數,其余的是一種自我記錄:在遵守給定約束的同時取三位數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.