46. Permutations (list)
来源:互联网 发布:收银软件dianqukeji 编辑:程序博客网 时间:2024/05/28 16:25
求一组不重复数的所有排列,用回溯法来遍历,不过这种回溯不需要回头。大概思路就是用一个递归函数,每次选择一个之前没选过的数加入到当前list中,最后如果选完了所有的数,加入到结果中。
算法并不难,主要是语法上遇到一些问题,比如关于list的使用。
总结:
1. list<list <Integer> > 这种二维的list,声明的时候还是和一维一样
results = new ArrayList<>();2.将一个list加入到results中时,语法应该是
results.add(new ArrayList<>(v) );3.list的remove操作,参数有对象和下标两种选择,如果要移除刚刚add进来的元素,可以写
v.remove(v.size() - 1);
完整代码:
import java.util.*;class Solution {List<List<Integer> > results; public List<List<Integer> > permute(int[] nums) { results = new ArrayList<>(); List<Integer> v = new ArrayList<Integer>(); re(v, nums); return results; } public void re(List<Integer> v, int [] nums) { if(v.size() == nums.length){results.add(new ArrayList<>(v) ); return ; } for(int i : nums) { if(!v.contains(i)) { v.add(i); re(v, nums); v.remove(v.size() - 1); } } }}
阅读全文
0 0
- 46. Permutations (list)
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 一篇对Spring Security框架理解的好文(注意一下评论区)
- PHP 应用性能优化方案
- 1989CSUOJ
- 静态代码分析工具列表--常用静态代码分析工具介绍
- PHP高效率写法(详解原因)
- 46. Permutations (list)
- 为测试赋能,腾讯WeTest探索手游AI自动化测试之路
- 高级编辑控件-CRichEditCtrl
- Spring Security OAuth2# Scope
- JVM堆栈跟踪之Jstack命令
- web前端人员到底如何处理浏览器兼容,到底什么是浏览器兼容问题
- Base64原理彻底弄清
- Python 守护线程
- 离职感言