LeetCode.无重复字符串的排列组合(Java 回溯)

无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例1: 输入:S = “qwe” 输出:[“qwe”, “qew”, “wqe”, “weq”, “ewq”, “eqw”]
示例2: 输入:S = “ab” 输出:[“ab”, “ba”]
提示:字符都是英文字母;字符串长度在[1, 9]之间

解法一:回溯
要理解回溯的思想:沿着可能的子路径一直走,直到走到尽头,还要返回到最前面的状态,又换一种可能的路径走,如此反复,直到走完全部的路径。
DFS模板:先定义终止条件,然后for循环,走遍所有可能的路径,没走完一条,要回退的前面的状态。

ArrayList<String> list = new ArrayList<>();

public String[] permutation(String S) {
    
    
	char[] cs = S.toCharArray();
	DFS(new StringBuilder(), cs, new HashSet<>(), S.length());
	String[] strings = new String[list.size()];
	for (int i = 0; i < list.size(); i++) {
    
    
		strings[i] = list.get(i);
	}
	return strings;
}

public void DFS(StringBuilder s, char[] cs, HashSet<Character> set, int n) {
    
    
	if (s.length() == n) {
    
    
		list.add(s.toString());
	} else {
    
    
		for (int i = 0; i < n; i++) {
    
    
			if (!set.contains(cs[i])) {
    
    
				set.add(cs[i]);
				s.append(cs[i]);
				DFS(s, cs, set, n);
				set.remove(cs[i]);
				s.deleteCharAt(s.length() - 1);
			}
		}
	}
}

解法二:标志位
基本思想与回溯类似。

class Solution {
    
    
	ArrayList<String> res = new ArrayList<String>();

	public String[] permutation(String S) {
    
    
		char[] chs = S.toCharArray();
		DFS("", chs, new boolean[chs.length]);
		String[] strs = new String[res.size()];
		for (int i = 0; i < res.size(); i++) {
    
    
			strs[i] = res.get(i);
		}
		return strs;
	}

	public void DFS(String cur, char[] chs, boolean[] flag) {
    
    
		if (cur.length() == chs.length) {
    
    
			res.add(cur);
		} else {
    
    
			for (int i = 0; i < chs.length; i++) {
    
    
				if (flag[i] == true)
					continue;
				flag[i] = true;
				DFS(cur + chs[i], chs, flag);
				flag[i] = false;
			}
		}

	}
}

end.

猜你喜欢

转载自blog.csdn.net/weixin_44998686/article/details/108574103