LeetCode: Permutations 解题报告

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 解题报告.

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] num) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (num == null || num.length == 0) {
 5             return ret;
 6         }
 7
 8         dfs(num, new ArrayList<Integer>(), ret);
 9         return ret;
10     }
11
12     public void dfs(int[] num, List<Integer> path, List<List<Integer>> ret) {
13         int len = num.length;
14         if (path.size() == len) {
15             ret.add(new ArrayList<Integer>(path));
16             return;
17         }
18
19         for (int i = 0; i < len; i++) {
20             if (path.contains(num[i])) {
21                 continue;
22             }
23
24             path.add(num[i]);
25             dfs(num, path, ret);
26             path.remove(path.size() - 1);
27         }
28     }
29 }

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.

 1 package Algorithms.permutation;
 2
 3 import java.util.ArrayList;
 4 import java.util.HashSet;
 5 import java.util.LinkedHashMap;
 6
 7 public class Permutation {
 8     public static void main(String[] strs) {
 9         int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9};
10         System.out.printf("Test size:%d \n", num.length);
11
12         Stopwatch timer1 = new Stopwatch();
13
14         permute(num);
15         System.out
16                 .println("Computing time with HASHMAP: "
17                         + timer1.elapsedTime() + " millisec.");
18
19         System.out.printf("Test size:%d \n", num.length);
20
21         Stopwatch timer2 = new Stopwatch();
22
23         permute2(num);
24         System.out
25                 .println("Computing time with list: "
26                         + timer2.elapsedTime() + " millisec.");
27     }
28
29     public static ArrayList<ArrayList<Integer>> permute(int[] num) {
30         ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
31         if (num == null) {
32             return ret;
33         }
34
35         permuteHelp(num, ret, new LinkedHashMap<Integer, Integer>());
36         return ret;
37     }
38
39     public static void permuteHelp(int[] num, ArrayList<ArrayList<Integer>> ret, LinkedHashMap<Integer, Integer> set) {
40         if (set.size() == num.length) {
41
42             ArrayList<Integer> list = new ArrayList<Integer>();
43             for (Integer i: set.keySet()){
44                 list.add(i);
45             }
46             ret.add(list);
47             return;
48         }
49
50         int len = num.length;
51         for (int i = 0; i < len; i++) {
52             if (set.containsKey(num[i])) {
53                 continue;
54             }
55
56             //path.add(num[i]);
57             set.put(num[i], 0);
58             permuteHelp(num, ret, set);
59             //path.remove(path.size() - 1);
60             set.remove(num[i]);
61         }
62     }
63
64     public static ArrayList<ArrayList<Integer>> permute2(int[] num) {
65         ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
66         if (num == null) {
67             return ret;
68         }
69
70         ArrayList<Integer> path = new ArrayList<Integer>();
71         permuteHelp2(num, path, ret);
72         return ret;
73     }
74
75     public static void permuteHelp2(int[] num, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> ret) {
76         if (path.size() == num.length) {
77             ret.add(new ArrayList<Integer>(path));
78             return;
79         }
80
81         int len = num.length;
82         for (int i = 0; i < len; i++) {
83             if (path.contains(num[i])) {
84                 continue;
85             }
86
87             path.add(num[i]);
88             permuteHelp2(num, path, ret);
89             path.remove(path.size() - 1);
90         }
91     }
92 }

GITHUB:

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

时间: 2024-10-06 23:21:00

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

[LeetCode]3Sum,解题报告

题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The so

[LeetCode]Candy, 解题报告

前言 回学校写论文差不多快二周的时间了,总结一句话,在学校真舒服.花了7天时间搞定了毕业论文初稿(之所以这么快肯定跟我这三年的工作量相关了),不过今天导师批复第二章还是需要修改.此外,最近迷上打羽毛球,确实很爽,运动量仅此于篮球,可以场地有限,哎,且打且珍惜吧. 题目 There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these chi

【LeetCode】Permutations 解题报告

全排列问题.常用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. [题目] 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

Single Number | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/single-number/ 题目描述: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without usin

Add Two Numbers | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/add-two-numbers/ 题目描述: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return i

Two Sum | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/two-sum/ 题目描述: Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, whe

LeetCode: isSameTree1 解题报告

isSameTree1 Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. SOLUTION 1 & SOLUTION 2: 以下是递归及非递归解法: 1. 递归解法就是判断当前节点是

LeetCode: Subsets 解题报告

Subsets Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1

LeetCode: solveSudoku 解题报告

Sudoku SolverWrite a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. SOLUTION: ref: http://blog.csdn.net/fightforyourdream/articl