Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
public class Permutations {

    public List<List<Integer>> permute(List<Integer> nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>()); for(int num: nums) {
int sz = result.size();
for(int i = 0; i < sz; ++i) {
List<Integer> old = result.get(i);
for(int j = 0; j <= old.size(); ++j) {
List<Integer> updated = new ArrayList<>(old);
updated.add(j, num);
result.add(updated);
}
}
result.subList(0, sz).clear();
}
return result;
} public static void main(String[] args) {
Permutations p = new Permutations();
List<List<Integer>> result = p.permute(Arrays.asList(1, 2, 3));
System.out.println(result);
}
}

Time complexity: O(n * n!) = O(0! + 1! + 2! + 3! + ...n!)

Iterative: staring with an empty array, { { } }

Adding number 1, { { } } ->{ { 1 } }

Adding number 2, { { 1 }  } ->{ { 2 , 1 }, { 1, 2 } }

Adding number 3: { { 2, 1 }, { 1, 2 } } -> { {3, 2, 1}, {2, 3, 1}, {2, 1, 3}, {3, 1, 2}, {1, 3, 2}, {1, 2, 3}}

Taken-out: start with something small, build the solution based on smaller inputs.

Recursive: backtracking, swapping elements to get new array

1. {1, 2, 3}  swap the first element with the rest, i = 0

2. After 1 swapped with itsself, {1, 2, 3}, swap the 2nd element with the rest, pos = 1

3. After 2 swapped with itselft, {1, 2, 3}, swap the 3rd element with the rest, pos = 2

4. After 3 swapped with iteself, {1, 2, 3}, you can either return here when pos == nums.size() or pos > nums.size(), result.add(new ArrayList<>(nums)), as base case. {{1, 2, 3}}

5. Back to step 3, 2 swapped with 3, {1, 3, 2}, swap the 3rd element with the rest, pos = 2

6. After 2 swapped with iteself, {1, 3, 2}. { {1, 2, 3}, {1, 3, 2} }

7. Backtracked to step 3, after the subcall which swapped 2 and 3, in order to return the nums to previous state before the subcall, we need to swap the elemtns back.

public class Permutations {
private void permuteHelper(int pos, List<Integer> nums, List<List<Integer>> result) {
int len = nums.size();
if(pos == len-1) {
result.add(new ArrayList<>(nums));
return;
} for(int i = pos; i < len; ++i) {
Collections.swap(nums, pos, i);
permuteHelper(pos+1, nums, result);
Collections.swap(nums, pos, i);
}
} public List<List<Integer>> permute(List<Integer> nums) {
List<List<Integer>> result = new ArrayList<>();
permuteHelper(0, nums, result);
return result;
} public static void main(String[] args) {
Permutations p = new Permutations();
List<List<Integer>> result = p.permute(Arrays.asList(1, 2, 3));
System.out.println(result);
}
}

Permutations LT46的更多相关文章

  1. Permutations II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  2. [LeetCode] Permutations II 全排列之二

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  3. [LeetCode] Permutations 全排列

    Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the follow ...

  4. POJ2369 Permutations(置换的周期)

    链接:http://poj.org/problem?id=2369 Permutations Time Limit: 1000MS   Memory Limit: 65536K Total Submi ...

  5. Permutations

    Permutations Given a collection of distinct numbers, return all possible permutations. For example,[ ...

  6. 【leetcode】Permutations

    题目描述: Given a collection of numbers, return all possible permutations. For example, [1,2,3] have the ...

  7. [leetcode] 47. Permutations II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  8. Leetcode Permutations

    Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the follow ...

  9. one recursive approach for 3, hdu 1016 (with an improved version) , permutations, N-Queens puzzle 分类: hdoj 2015-07-19 16:49 86人阅读 评论(0) 收藏

    one recursive approach to solve hdu 1016, list all permutations, solve N-Queens puzzle. reference: t ...

随机推荐

  1. Spring设置动态定时任务

    1.在Spring中经常会用到定时任务,一般会在业务方法上使用@Schedule(cron="定时执行规则"),无法实现从前台动态设置定时任务. 在java中固定频率的任务使用Sc ...

  2. WPF HyperLink链接下划线隐藏

    两种方法: 1.在Grid标签内添加资源样式. <Grid.Resources> <Style TargetType="Hyperlink"> <Se ...

  3. cdh5.13.1 hadoop hdfs HA模式无法启动

    经过观察日志发现,JN三个节点启动正常,只有NN节点启动时提示JN节点没有格式化 停止HDFS下面所有服务 先启动JN节点 然后启动一个NN节点,观察三个JN节点日志 发现其中一个节点的日志正常,没有 ...

  4. matlab画图标题自定义字体大小

    title('标题','fontname','Times New Roman','Color','b','FontSize',20);字体是Times New Roman,颜色是蓝色('b'即blue ...

  5. cf-Global Round2-C. Ramesses and Corner Inversion(思维)

    题目链接:http://codeforces.com/contest/1119/problem/C 题意:给两个同型的由0.1组成的矩阵A.B,问A能否经过指定的操作变成B,指定操作为在矩阵A中选定一 ...

  6. enlarge your dataset

    列举常见的几种数据集增强方法: 1.flip  翻折(左右,上下) # NumPy.'img' = A single image. flip_1 = np.fliplr(img) # TensorFl ...

  7. df.dropna()函数和df.ix(),df.at(),df.loc()

  8. 音频播放 音乐 MediaPlayer

    MediaPlayer对象的生命周期如下: Idle 状态:当使用new()方法创建一个MediaPlayer对象或者调用了其reset()方法时,该MediaPlayer对象处于idle状态.这两种 ...

  9. stm32学习基本知识点

    1.AHB系统总线分为APB1(36MHz)和APB2(72MHz),其中2>1,意思是APB2接高速设备 2.Stm32f10x.h相当于reg52.h(里面有基本的位操作定义),另一个为st ...

  10. [剑指Offer]6-从尾到头打印链表

    典型的后进先出,可以借助栈,也可以使用递归. 考虑到若链表过长递归可能造成函数调用栈溢出,所以使用栈更好. 注意stack无遍历操作,全部用push(),pop(),top()完成. 以下创建列表胡乱 ...