剑指offer (27)

题目 : 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

思路 :

在这里插入图片描述

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
	public static void main(String[] args) {
		Solution solution = new Solution();
		System.out.println(solution.permution("abc"));
	}
	public ArrayList<String> permution(String string){
		ArrayList<String> res = new ArrayList<>();
		if (string != null && string.length() > 0) {
			permutationHelper(string.toCharArray(), 0, res);
			Collections.sort(res);
		}
		return res;
	}
	public void permutationHelper(char [] cs ,int i , ArrayList<String> list) {
		if (i == cs.length - 1) {
			String val = String.valueOf(cs);
			if (!list.contains(val)) {
				list.add(val);
			}
		}
		else {
			for (int j = i; j < cs.length; j++) {
				swap(cs, i, j);
				permutationHelper(cs, i+1, list);
				swap(cs, i, j);
			}
		}
	}
	public void swap(char [] cs,int i, int j) {
		char temp = cs[i];
		cs[i] = cs[j];
		cs[j] = temp;
	}
}
发布了50 篇原创文章 · 获赞 0 · 访问量 400

猜你喜欢

转载自blog.csdn.net/weixin_46108108/article/details/104202060