【问题标题】:all possible permutations of digits in a given number给定数字中所有可能的数字排列
【发布时间】:2012-10-12 17:06:54
【问题描述】:

用户应该输入他的号码有多少位,然后他应该输入他的号码。然后代码应该以所有可能的方式排列该数字,而不是递归。

例如数字 123 可以有 6 种排列方式:

123 132 213 231 312 321

只是一个旁注,如果我提出这个问题的方式有问题,或者如果需要更多信息,请告诉我。即使你不知道我的问题的答案。我真的需要回答这个问题,我想我开始发疯了。

【问题讨论】:

  • 如果数字是101,是否要将两个不同的110 答案算作不同的排列?
  • 欢迎来到 Stackoverflow。请在问题中展示你的努力,而不是提出问题并期待答案。

标签: arrays algorithm database-design loops discrete-mathematics


【解决方案1】:

这相当于生成所有排列。

For generating the next permutation after the current one(the first one is 123):
  1. Find from right to left the first position pos where current[pos] < current[pos + 1]
  2. Increment current[pos] to the next possible number(some numbers are maybe already used)
  3. At the remaining positions(> pos) put the smallest possible numbers not used.
  4. Go to 1.

这是一个工作代码,打印所有排列:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        final int n = 3;

        int[] current = new int[n];
        for (int i = 1; i <= n; i++) {
            current[i - 1] = i;
        }

        int total = 0;
        for (;;) {
            total++;

            boolean[] used = new boolean[n + 1];
            Arrays.fill(used, true);

            for (int i = 0; i < n; i++) {
                System.out.print(current[i] + " ");
            }

            System.out.println();

            used[current[n - 1]] = false;

            int pos = -1;
            for (int i = n - 2; i >= 0; i--) {              
                used[current[i]] = false;

                if (current[i] < current[i + 1]) {
                    pos = i;
                    break;
                }
            }

            if (pos == -1) {
                break;
            }               

            for (int i = current[pos] + 1; i <= n; i++) {
                if (!used[i]) {
                    current[pos] = i;
                    used[i] = true;
                    break;
                }
            }

            for (int i = 1; i <= n; i++) {
                if (!used[i]) {
                    current[++pos] = i;
                }
            }
        }

        System.out.println(total);
    }       
}

附:我刚刚在几分钟内编写了代码。我没有声称代码是干净的或变量被命名为好。

【讨论】:

  • 啊!转到!恐慌!
【解决方案2】:

一点点googling,你会发现一些算法,例如Johnson-Trotter Algorithm,可以用5行来描述:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多