*LeetCode-Permutation
来源:互联网 发布:win7固态硬盘开机优化 编辑:程序博客网 时间:2024/04/28 03:20
两种思路 一种是从第一个数开始add 之后每个数add就是在上一条n个数中选一个位置insert 共n+1种
这种就是浪费了一些小的list 因为下面要复制sublist
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); helper ( res, nums, new ArrayList<Integer>(), 0 ); return res; } public void helper ( List<List<Integer>> res, int [] nums, List<Integer> temp, int k ){ if ( k >= nums.length ){ res.add ( temp ); return; } for ( int i = 0; i <= temp.size(); i ++ ){ List<Integer> next = new ArrayList<Integer>(temp); ////这里 next.add ( i, nums [ k ] ); helper ( res, nums, next, k + 1 ); } }}
不需要浪费空间的方法就是直接用原来的nums swap 每次固定一个数字在第一个位置上 然后recursive下面的位置
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); helper ( res, nums, 0 ); return res; } public void helper ( List<List<Integer>> res, int [] nums, int k ){ if ( k >= nums.length ){ List<Integer> temp = new ArrayList<Integer> (); for ( int i = 0; i < nums.length; i ++ ) temp.add ( nums [ i ] ); res.add ( temp ); return; } for ( int i = k; i < nums.length; i ++ ){ swap ( nums, i , k ); helper ( res, nums, k + 1 ); swap ( nums, i , k ); } } public void swap ( int [] nums, int i, int j ) { int temp = nums [ i ]; nums [ i ] = nums [ j ]; nums [ j ] = temp; }}
0 0
- LeetCode Permutation
- [LeetCode] Permutation
- LeetCode-Permutation
- Leetcode--Permutation
- Permutation--LeetCode
- leetcode permutation
- *LeetCode-Permutation
- LeetCode之Permutation、Permutation II
- leetcode -- Permutation & Permutation II--重点
- LeetCode: Next Permutation
- LeetCode: Permutation Sequence
- LeetCode Next Permutation
- LeetCode Permutation Sequence
- LeetCode : Next Permutation
- [Leetcode] Permutation Sequence
- [Leetcode] Next Permutation
- [LeetCode] Next Permutation
- [LeetCode] Permutation Sequence
- Java之随机数
- Linux 编译报错 undefined reference to `pthread_create'
- uva10635 Prince and Princess(LCS转LIS)
- 计算几何 uva11117 Morley's Theorem
- ActiveMQ LevelDB持久化机制
- *LeetCode-Permutation
- 将VS2012的项目转化为VS2010
- 在Android studio中建立Java工程
- TSP问题
- 关于C#类中重写ToString方法和PHP类中__tostring()方法的比较
- PageAdapter不能刷新问题
- Week2-5Spelling similarity:edit distance
- 我
- Android使用.9图片失效的问题