Permutations
来源:互联网 发布:mac 怎么让终端翻墙 编辑:程序博客网 时间:2024/06/05 17:12
Problem:
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:
public class Solution {
boolean[] isUsed;
List<List<Integer>> res;
List<Integer> tmp;
int[] A;
public List<List<Integer>> permute(int[] num) {
res = new ArrayList<List<Integer>>();
if(num==null||num.length==0)
return res;
A = num;
isUsed = new boolean[A.length];
tmp = new ArrayList<>();
permuting();
return res;
}
private void permuting(){
if(tmp.size()==A.length)
res.add(new ArrayList<>(tmp));
for(int i=0;i<A.length;i++)
if(!isUsed[i])
{
isUsed[i] = true;
tmp.add(A[i]);
permuting();
tmp.remove(tmp.size()-1);
isUsed[i] = false;
}
}
}
boolean[] isUsed;
List<List<Integer>> res;
List<Integer> tmp;
int[] A;
public List<List<Integer>> permute(int[] num) {
res = new ArrayList<List<Integer>>();
if(num==null||num.length==0)
return res;
A = num;
isUsed = new boolean[A.length];
tmp = new ArrayList<>();
permuting();
return res;
}
private void permuting(){
if(tmp.size()==A.length)
res.add(new ArrayList<>(tmp));
for(int i=0;i<A.length;i++)
if(!isUsed[i])
{
isUsed[i] = true;
tmp.add(A[i]);
permuting();
tmp.remove(tmp.size()-1);
isUsed[i] = false;
}
}
}
0 0
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- 从架构到代码演练
- 重载(overload)、覆盖(override)和隐藏(hide)
- Notepad++文本比较插件:Compare
- 睡眠十律()
- 实时监听输入框值变化的完美方案(兼容ie):oninput & onpropertychange
- Permutations
- NPOI创建DOCX常用操作
- centos6下memcached-1.4.13的安装,启动和关闭等
- Android上传图片关键代码
- C#中各种计时器
- jQuery如何获取同一个类标签的所有值(默认无法获取)
- BZOJ 3732 Network Link-Cut-Tree (我是认真的!!
- This account is currently not available
- 面向过程与面向对象