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]
]

The idea is using recursive approach, we can define a recursive function

helper(prefix, suffix, result)

Where the prefix is: for example

[1]

suffix:

[2, 3]

So every time, we take one value from suffix, put into prefix.

The stop logic is that when suffix length is zero, then we push the prefix into result.

if (sfx.length === 0) {
result.push(pfx);
}
/**
* @param {number[]} nums
* @return {number[][]}
*/
var permute = function(nums) {
function helper (pfx, sfx, result) {
if (sfx.length === 0) {
result.push(pfx);
} else {
const len = sfx.length;
for (let i = 0; i < len; i++) {
helper(
pfx.concat(sfx[i]),
sfx.slice(0, i).concat(sfx.slice(i+1, sfx[len])),
result
);
}
} return result;
} return helper([], nums, []);
}; permute([1,2,3]) /* [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] */
[], [1,2,3]

[1], [2,3]

[1, 2], [3], [] | [1, 3], [2] 

---> [1,2,3] | [1,2,3]

[2], [1, 3]
[2, 1], [3] | [2,3] [1] --> [2,1,3] | [2,3,1] [3], [1,2]
[3,1][2] | [3,2], [1] --> [3,1,2] | [3,2,1]

最新文章

  1. 重复发起Volley请求不要使用同一对象
  2. duilib进阶教程 -- 总结 (17)
  3. 免费素材下载:iOS 8 矢量 UI 素材套件
  4. zabbix自定义键值原理
  5. Embedded Database service fails to start after installing or migrating to Symantec Endpoint Protection (SEP) 12.1.5 (RU5)
  6. SPOJ8222 Substrings( 后缀自动机 + dp )
  7. Recover the String
  8. (简单) HDU 2612 Find a way,BFS。
  9. 基于require+knockout的webapp结构设计
  10. Spring AOP分析(1) -- 基本概念
  11. NetBeans部署项目(Extjs)报错(一)
  12. Go语言初篇
  13. 《jQuery精品教程视频》-每天的复习笔记
  14. Atitit easyui翻页组件与vue的集成解决方案attilax总结
  15. linux_磁盘挂载
  16. jQuery~DOM基础操作
  17. android studio 3.0 安装配置
  18. C/C++ Volatile关键词深度剖析
  19. 数数字 (Digit Counting,ACM/ICPC Dannang 2007 ,UVa1225)
  20. jQuery中resetForm与clearForm的区别?

热门文章

  1. Akka-CQRS(12)- akka-http for http-web-service: Routing-服务项目接口
  2. Mysql——查看数据库,表占用磁盘大小
  3. [转] Vue原理解析——自己写个Vue
  4. Bagging 和RF的区别
  5. SQL server中常用sql语句
  6. 2019 中至数据java面试笔试题 (含面试题解析)
  7. 封装axios,带请求头和响应头
  8. Spark ML协同过滤推荐算法
  9. svn进行上传项目
  10. Linux服务器相关信息查询