Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

SOLUTION 1:

经典的递归回溯题目,一次ACCEPT. 请也参考上一个题目LeetCode: Combinations 解题报告.

 public class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (num == null || num.length == 0) {
return ret;
} dfs(num, new ArrayList<Integer>(), ret);
return ret;
} public void dfs(int[] num, List<Integer> path, List<List<Integer>> ret) {
int len = num.length;
if (path.size() == len) {
ret.add(new ArrayList<Integer>(path));
return;
} for (int i = 0; i < len; i++) {
if (path.contains(num[i])) {
continue;
} path.add(num[i]);
dfs(num, path, ret);
path.remove(path.size() - 1);
}
}
}

SOLUTION 2:

可能有的同学觉得为什么path.contains不用hashmap来代替哩?所以主页君写了一个带hashmap的版本。结论是,在这个set规模小的时候,hashmap的性能还不

如arraylist。

原因可能在于,hashmap申请的不是一个连续的空间,而arraylist比较小的话,直接在连续内存中操作,速度会比较快。

以下是此程序的运行结果,hashmap的版本速度要慢一倍:

Test size:9
Computing time with HASHMAP: 629.0 millisec.
Test size:9
Computing time with list: 310.0 millisec.

 package Algorithms.permutation;

 import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap; public class Permutation {
public static void main(String[] strs) {
int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.printf("Test size:%d \n", num.length); Stopwatch timer1 = new Stopwatch(); permute(num);
System.out
.println("Computing time with HASHMAP: "
+ timer1.elapsedTime() + " millisec."); System.out.printf("Test size:%d \n", num.length); Stopwatch timer2 = new Stopwatch(); permute2(num);
System.out
.println("Computing time with list: "
+ timer2.elapsedTime() + " millisec.");
} public static ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (num == null) {
return ret;
} permuteHelp(num, ret, new LinkedHashMap<Integer, Integer>());
return ret;
} public static void permuteHelp(int[] num, ArrayList<ArrayList<Integer>> ret, LinkedHashMap<Integer, Integer> set) {
if (set.size() == num.length) { ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i: set.keySet()){
list.add(i);
}
ret.add(list);
return;
} int len = num.length;
for (int i = 0; i < len; i++) {
if (set.containsKey(num[i])) {
continue;
} //path.add(num[i]);
set.put(num[i], 0);
permuteHelp(num, ret, set);
//path.remove(path.size() - 1);
set.remove(num[i]);
}
} public static ArrayList<ArrayList<Integer>> permute2(int[] num) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (num == null) {
return ret;
} ArrayList<Integer> path = new ArrayList<Integer>();
permuteHelp2(num, path, ret);
return ret;
} public static void permuteHelp2(int[] num, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> ret) {
if (path.size() == num.length) {
ret.add(new ArrayList<Integer>(path));
return;
} int len = num.length;
for (int i = 0; i < len; i++) {
if (path.contains(num[i])) {
continue;
} path.add(num[i]);
permuteHelp2(num, path, ret);
path.remove(path.size() - 1);
}
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/Permute.java

LeetCode: Permutations 解题报告的更多相关文章

  1. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  2. 【LeetCode】46. Permutations 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 方法一:库函数 方法二:递归 方法三:回溯法 日期 题目地址:h ...

  3. leetcode—Palindrome 解题报告

    1.题目描述 Given a string s, partition s such that every substring of the partition is a palindrome. Ret ...

  4. LeetCode C++ 解题报告

    自己做得LeetCode的题解,使用C++语言. 说明:大多数自己做得,部分参考别人的思路,仅供参考; GitHub地址:https://github.com/amazingyyc/The-Solut ...

  5. C++版 - 剑指offer之面试题37:两个链表的第一个公共结点[LeetCode 160] 解题报告

    剑指offer之面试题37 两个链表的第一个公共结点 提交网址: http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?t ...

  6. LeetCode: Subsets 解题报告

    Subsets Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset ...

  7. LeetCode: Triangle 解题报告

    Triangle Given a triangle, find the minimum path sum from top to bottom. Each step you may move to a ...

  8. LeetCode: isSameTree1 解题报告

    isSameTree1 Given two binary trees, write a function to check if they are equal or not. Two binary t ...

  9. LeetCode: Combinations 解题报告

    Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... ...

随机推荐

  1. 在jsp页面上打印错误堆栈

    try{ .................... } catch(Exception e){ //定义一个流 ByteArrayOutputStream ostr = new ByteArrayOu ...

  2. Theano Logistic Regression

    原理 逻辑回归的推理过程能够參考这篇文章:http://blog.csdn.net/zouxy09/article/details/20319673,当中包括了关于逻辑回归的推理,梯度下降以及pyth ...

  3. python字符串格式化--dict传参

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python字符串格式化--dict传参 print "I'm %(name)s. I'm %(a ...

  4. global语句(python学习手册422页)

    # -*- coding: cp936 -*- #python 27 #xiaodeng #global语句(python学习手册422页) #实际上就是一个名为__builtin__的模块,但是必须 ...

  5. 推荐10 款 SVG 动画的 JavaScript 库

    SVG 通常可以用作跨分辨率视频.这意味着在一块高分屏幕上不会降低图片的锐度.此外,你甚至可以让SVG动起来,通过使用一些javascript类库.下面,我们分享一些javascript类库,这些类库 ...

  6. Nginx中Laravel的配置

    server { listen 80; server_name sub.domain.com; set $root_path '/var/www/html/application_name/publi ...

  7. BIND9源码分析之 多个view的情况下如何做dynamic update

    BIND中view的存在提供了一种较好的智能DNS方案,BIND可以根据用户的来源IP为其返回不同的Resource Record. 但是关于DNS动态更新的RFC2136中并没有提及view(vie ...

  8. Java编程性能优化一些事儿【转】

    原文出处: 陶邦仁 在JAVA程序中,性能问题的大部分原因并不在于JAVA语言,而是程序本身.养成良好的编码习惯非常重要,能够显著地提升程序性能. 1. 尽量在合适的场合使用单例 使用单例可以减轻加载 ...

  9. Asp.Net Core 轻松学-一行代码搞定文件上传 JSONHelper

    Asp.Net Core 轻松学-一行代码搞定文件上传   前言     在 Web 应用程序开发过程中,总是无法避免涉及到文件上传,这次我们来聊一聊怎么去实现一个简单方便可复用文件上传功能:通过创建 ...

  10. 竞态条件与sigsuspend函数

    一.利用pause和alarm函数实现sleep函数 #include <unistd.h> int pause(void); pause函数使调用进程挂起直到有信号递达.如果信号的处理动 ...