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