博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] Permutations
阅读量:7054 次
发布时间:2019-06-28

本文共 1171 字,大约阅读时间需要 3 分钟。

hot3.png

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

思路:生成permutation,这题假设没有重复元素,递归求解,每一次在cur位置填元素,添之前判断钙元素是否已经用过,没用过继续下去,指导cur==n。

public class Solution {	public ArrayList
> permute(int[] num) { if (num == null) return null; ArrayList
> res = new ArrayList
>(); if (num.length == 0) return res; int[] permSeq = new int[num.length]; perm(num.length, 0, num, permSeq, res); return res; } private void perm(int n, int cur, int[] num, int[] perm, ArrayList
> res) { if (cur == n) { ArrayList
tmp = new ArrayList
(); for (int i = 0; i < perm.length; i++) { tmp.add(perm[i]); } res.add(tmp); } else { int i; for (i = 0; i < num.length; i++) { int j; boolean ok = true; for (j = cur - 1; j >= 0; j--) { if (perm[j] == num[i]) ok = false; } if (ok) { perm[cur] = num[i]; perm(n, cur + 1, num, perm, res); } } } } public static void main(String[] args) { System.out.println(new Solution().permute(new int[] { 1, 2, 3,4 })); }}

转载于:https://my.oschina.net/jdflyfly/blog/284302

你可能感兴趣的文章
动态域名搭建exchang邮箱服务器
查看>>
Jquery实现新闻上下滚动效果
查看>>
CGI?
查看>>
使用postMessage实现跨窗口消息传递
查看>>
VIM跳转和小改动
查看>>
svn 常用指令 及 常见问题记录
查看>>
修改全志A10, A20的Nand分区大小
查看>>
python class和class(object)用法区别
查看>>
ejs标签
查看>>
我的友情链接
查看>>
Linux/Unix批量处理产生
查看>>
XFS和RAID6性能优化
查看>>
corosync+pacemaker 实现高可用集群(三)
查看>>
linux下的java开发环境
查看>>
Bootstrap使用记录
查看>>
从一场场大型网站灾难过后的BUG:根
查看>>
Linux系统下怎样利用nc命令来监控检测服务器的端口使用情况
查看>>
git命令总结
查看>>
tomcat高访问jvm配置
查看>>
谢烟客---------二进制安装MariaDB,管理关系型数据库的基本组件
查看>>