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. maven Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4

      maven Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4 CreateTime--201 ...

  2. 一个简单的knockout.js 和easyui的绑定

    <!DOCTYPE html><html><head><meta charset="UTF-8"><title>Basi ...

  3. 对UserDict的研究

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #对UserDict的研究 class UserDict(): def __init__(self, dict ...

  4. ModelAndView 配置与使用

    一,ModelAndView 介绍: 1)ModelAndView 用于后台与前端页面交互: 2)可以用于重定向与转发到指定页面, 3)可以保存数据然后渲染到页面 二,使用: 1)在Controlle ...

  5. Java开源内容管理CMS系统J4CMS集成到JTM

    JTM是Win32下绿色免费的JDK + Tomcat + MySQL环境集成工具. 通过JTM用户无需对JDK.Tomcat.MySQL进行不论什么安装和配置就可以迅速搭建支持JSP + MySQL ...

  6. JSP,servlet和数据库之间传值出现乱码的问题

     近期困扰我非常久的一个问题最终攻克了,为他我头疼了好几天,问题是JSP通过servlet向数据库传值,查询显示在页面的时候出现了乱码,原先我数据库中有两行带有中文的数据,查询的时候倒是没有出现乱 ...

  7. linux账户密码安全策略

    前言 对于服务器安全来说,服务器的账号密码是很重要的事情 我们可以选择取消账号密码登陆,只使用公钥登录,但有时可能并不方便 这里告诉大家账号密码如何管理更加安全 一.账号密码最大使用天数 在/etc/ ...

  8. ACM遇到的问题与解决方案

    C++防止栈溢出措施: 只要在你的代码里加上下面这句话, OK,栈溢出直接搞定!!! #pragma comment(linker, "/STACK:102400000,102400000& ...

  9. HDUOJ-------Being a Good Boy in Spring Festival

    Being a Good Boy in Spring Festival Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32 ...

  10. 在python中使用静态方法staticmethod

    静态方法: 静态方法是类中的函数,不需要实例.静态方法主要是用来存放逻辑性的代码,主要是一些逻辑属于类,但是和类本身没有交互,即在静态方法中,不会涉及到类中的方法和属性的操作.可以理解为将静态方法存在 ...