求不重复字符字符串的全排列
2015-09-02 22:03
411 查看
题目:输入一个自付出,打印出该字符串的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc,acb,bac,bca,cab,cba.
思路:将第一个字符与其后面字符分成两部分,将第一个字符与后面每个字符交换,不断递归。
代码如下:
思路:将第一个字符与其后面字符分成两部分,将第一个字符与后面每个字符交换,不断递归。
代码如下:
import java.util.Arrays; public class FullPermutation { public static int k=0; public void Permutation(char[] s) { if(s==null) { return; } Permutation( s, 0); } public void Permutation(char[] s,int position) { if(position==s.length-1) { System.out.println(++k+":"+Arrays.toString(s)); } else { for(int i=position;i<s.length;i++) { char temp=s[i]; s[i]=s[position]; s[position]=temp; Permutation(s, position+1); temp=s[i]; s[i]=s[position]; s[position]=temp; } } } public static void main(String[] args) { String s="abcd"; FullPermutation p=new FullPermutation(); p.Permutation(s.toCharArray()); } }输出结果:
1:[a, b, c, d] 2:[a, b, d, c] 3:[a, c, b, d] 4:[a, c, d, b] 5:[a, d, c, b] 6:[a, d, b, c] 7:[b, a, c, d] 8:[b, a, d, c] 9:[b, c, a, d] 10:[b, c, d, a] 11:[b, d, c, a] 12:[b, d, a, c] 13:[c, b, a, d] 14:[c, b, d, a] 15:[c, a, b, d] 16:[c, a, d, b] 17:[c, d, a, b] 18:[c, d, b, a] 19:[d, b, c, a] 20:[d, b, a, c] 21:[d, c, b, a] 22:[d, c, a, b] 23:[d, a, c, b] 24:[d, a, b, c]
相关文章推荐
- Leetcode #238 Product of Array Except Self
- QT 多线程程序设计
- Linux命令备忘实例(3)——数学运算
- 亚马逊与微软赢得一亿美元云计算合约,IBM黯然神伤
- 什么样的项目适合自动化测试
- 数据库校招笔试题(1)
- 树状数组求区间最大值
- Python游戏服务器开发日记(五)skynet_messagequeue和skynet_timer
- UIActivityIndicatorView活动指示条
- OC04_属性
- LeetCode 9_Palindrome Number
- lintcode-子树
- poj1860 Currency Exchange (bellman_ford)
- Java字符流与字节流的区别
- python做全文检索引擎
- SQL server 数据库远程连接
- poj 3613 矩阵快速幂变形(恰好k条边最短路)
- 静态查找表
- 【bzoj3680】【吊打XXX】【模拟退火】
- (JavaScript)案例二:多条件查询