开发者社区 问答 正文

生成用0到9这十个数字所有的排列组合的例子

用 0到9 生成 十位数的所有排列组合,数字0不能在第一个,这个生成的十位数,
不能有重复的数字。

展开
收起
蛮大人123 2016-05-31 09:05:43 3615 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    public static void main(String[] args) {
            String str[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            permutation(str, 0, str.length);
        }
    
        static void swap(String[] str, int start, int end) {
            String tmep = str[start];
            str[start] = str[end];
            str[end] = tmep;
        }
    
        static void permutation(String[] str, int start, int end) {
    
            if (start == end - 1) {
                for (int i = 0; i < end; i++) {
                    System.out.print(str[i]);
                }
                System.out.println();
            } else {
    
                for (int i = start; i < end; i++) {
                    if (i == 0 && str[0].equals("0"))
                        continue;
                    swap(str, start, i);
                    permutation(str, start + 1, end);
    
                    swap(str, start, i);
                }
            }
        }
    }
    2019-07-17 19:21:15
    赞同 展开评论
问答地址: