首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

怎么产生所有的数字序列

2013-09-06 
如何产生所有的数字序列。比如1 2 3结果:123132213231312321[解决办法]void perm (int [] source, int [] r

如何产生所有的数字序列。
比如1 2 3
结果:
1  2  3
1  3  2
2  1  3
2  3  1
3  1  2
3  2  1


[解决办法]

void perm (int [] source, int [] result, int index) {
  for (int i = 0; i < source.length; i ++) {
    for (int j = 0; j < index; j++) {
      if (source[i] == result[j])
        continue;
      break;
    }
    result[index] = source[i];
    break;
  }
  if (index == source.length -1)
    return;
  perm(source, result, index+1);
}

int[] source = {1, 2, 3};
int[] result = new int[3];
perm(source, result, 0);


没调试过,大概是不对的吧。。
[解决办法]
引用:
Quote: 引用:

可以考虑考虑用递归,之前在学校的时候写过,好久没搞算法了

是不是比较麻烦。
我开始以为是一个简单的问题....

不是很麻烦,我到网上帮你找了一个,你看看

#include <stdio.h>
#include <string.h>

char string[]="123456789a";
int used[10]={0};
char output[10];
int length;

void Fun(int d)
{
int i;

for(i=0;i<=length;i++)
{
if(!used[i])
{
used[i]=1;
output[d]=string[i];
if(d==length)
{
for(d=0;d<length;d++)
{
if(output[d]=='a')
printf("10 ");
else printf("%c ",output[d]);
}
if(output[length]=='a')
printf("10\n");
else
printf("%c\n",output[length]);
}
else
Fun(d+1);
used[i]=0;
}
}
}

int main()


{
int n;
scanf("%d",&n);

string[n]=0;
length=strlen(string)-1;

Fun(0);

return 0;
}


[解决办法]
随意几个数,只要输入就可以了。

public class Test4 {
public static void main(String[] args) {
        String test = "123";
        char[] chars = test.toCharArray();
        allSort(chars, 0, chars.length - 1);
    }
 
    private static StringBuilder TEMP = new StringBuilder();
 
    public static void allSort(char[] buf, int start, int end) {
        if (start == end) {
            for (int i = 0; i <= end; i++) {
                TEMP.append(buf[i]);
            }
            numberChecker();
        } else {
            for (int i = start; i <= end; i++) {
                char temp = buf[start];
                buf[start] = buf[i];
                buf[i] = temp;
 
                allSort(buf, start + 1, end);
 
                temp = buf[start];
                buf[start] = buf[i];
                buf[i] = temp;
            }
        }
    }
 
    private static void numberChecker() {


    System.out.println(TEMP);
        TEMP.replace(0, TEMP.length(), "");
    }
}

热点排行