leetcode:Permutations (序列所有排列)【面试算法题】
2013-10-17 15:49
573 查看
题目:
Given a collection of numbers, return all possible permutations.
For example,
and
题意输出给定序列的所有排列。
用dfs去遍历所有可能的序列,data记录结果序列中第i个数在num中的位置,sign记录深度遍历中num中每个值是否已经使用过,防止重复遍历。
当index=n时,表示遍历完,用result存当前符合条件的序列。
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].
题意输出给定序列的所有排列。
用dfs去遍历所有可能的序列,data记录结果序列中第i个数在num中的位置,sign记录深度遍历中num中每个值是否已经使用过,防止重复遍历。
当index=n时,表示遍历完,用result存当前符合条件的序列。
class Solution { private: vector<vector<int> >result; int data[10]; int sign[10]; public: vector<vector<int> > permute(vector<int> &num) { result.clear(); memset(sign,0,sizeof(sign)); int n=num.size(); dfs(n,0,num); return result; } void dfs(int n,int index,vector<int> &num) { if(index==n) { vector<int >t; for(int i=0;i<n;++i)t.push_back(num[data[i]]); result.push_back(t); return; } for(int i=0;i<n;++i) { if(sign[i]==0) { sign[i]=1; data[index]=i; dfs(n,index+1,num); sign[i]=0; } } } }; // http://blog.csdn.net/havenoidea[/code]
相关文章推荐
- leetcode:Permutations II (序列所有无重复排列)【面试算法题】
- leetcode:Permutation Sequence (顺序排列第k个序列) 【面试算法题】
- 【LeetCode-面试算法经典-Java实现】【046-Permutations(求排列)】
- leetcode:Reorder List (修改链表排列不改变值) 【面试算法题】
- 【LeetCode】 Permutations 排列生成算法之字典序法
- 微软等数据结构+算法面试100题(2)--给出一个函数来输出一个字符串的所有排列
- leetcode:Median of Two Sorted Arrays (找两个序列的中位数,O(log (m+n))限制) 【面试算法】
- leetcode:Populating Next Right Pointers in Each Node(常数空间,连接二叉树每一层所有节点)【面试算法题】
- 【算法面试】写程序输出8皇后问题的所有排列,要求使用非递归的深度优先遍历。
- Median of Two Sorted Arrays (找两个序列的中位数,O(log (m+n))限制) 【面试算法leetcode】
- leetcode:Distinct Subsequences (不同的子序列)【面试算法题】
- leetcode--Permutations(打印所有排列)
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(所有根到叶子结点组组成的数字相加)】
- 【LeetCode-面试算法经典-Java实现】【030-Substring with Concatenation of All Words(串联所有单词的子串)】
- Longest Consecutive Sequence (最长连续序列) 【面试算法leetcode】
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- leetcode:Next Permutation (求下一个排列) 【面试算法题】
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- 【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
- 一个组合加全排列的面试算法题及其解