深度优先-Leetcode46 全排列
2017-06-23 12:55
357 查看
Given a collection of distinct 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].
深度优先的框架:
public class Solution {
//深度优先 的框架
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static boolean[] v = new boolean[100];
public static void robot(int idx, int[] nums){
if(idx >= nums.length){
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++){
tmp.add(nums[path[i]]);
}
ans.add(tmp);
return;
}
for(int i = 0; i < nums.length; i++){
if(v[i] == false){
path[idx] =i;
v[i] = true;
robot(idx+1, nums);
v[i] = false;
}
}
}
public List<List<Integer>> permute(int[] nums) {
ans.clear();
robot(0,nums);
return ans;
}
}
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].
深度优先的框架:
public class Solution {
//深度优先 的框架
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static boolean[] v = new boolean[100];
public static void robot(int idx, int[] nums){
if(idx >= nums.length){
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++){
tmp.add(nums[path[i]]);
}
ans.add(tmp);
return;
}
for(int i = 0; i < nums.length; i++){
if(v[i] == false){
path[idx] =i;
v[i] = true;
robot(idx+1, nums);
v[i] = false;
}
}
}
public List<List<Integer>> permute(int[] nums) {
ans.clear();
robot(0,nums);
return ans;
}
}
相关文章推荐
- leetcode 526. Beautiful Arrangement 递归实现全排列 + 经典深度优先遍历DFS做法
- leetcode 529. Minesweeper 扫雷游戏 + 经典的DFS深度优先遍历
- LeetCode 之 DFS 深度优先遍历
- leetcode 464. Can I Win 100相加游戏 + 一个十分棒的深度优先遍历DFS的做法
- leetcode 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化 + 深度优先遍历DFS
- leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历 + 很明显很经典的DP动态规划做法
- leetcode 131. Palindrome Partitioning 按照index做DFS深度优先遍历
- leetcode 404. Sum of Left Leaves 所有左孩子叶节点之和计算 + 深度优先遍历DFS
- LeetCode 46 Permutations (全排列)
- leetcode 623. Add One Row to Tree二叉树添加指定深度元素+ 深度优先遍历DFS
- leetcode 22. Generate Parentheses DFS深度优先遍历
- leetcode 78. Subsets DFS深度优先搜索
- leetcode 111. Minimum Depth of Binary Tree DFS深度优先遍历 + 添加对叶子节点判断
- leetcode_permutaionu全排列集合_31_46_47_60
- leetcode 329. Longest Increasing Path in a Matrix 矩阵中寻找最长递增序列 + 一个典型的深度优先遍历DFS的做法
- leetcode 606. Construct String from Binary Tree 前序遍历 + 深度优先遍历DFS
- leetcode 100. Same Tree 二叉树DFS深度优先遍历
- leetcode 98. Validate Binary Search Tree DFS深度优先搜索 + 两个递归函数 + 一个错误做法
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- LeetCode-46 Permutations(全排列)