JZ27 字符串的排列
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&&tqId=11180&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
排列问题
for循环 每次选一个字符 然后递归
import java.util.*; public class Solution { ArrayList<String> res = new ArrayList<>(); char[] c; public ArrayList<String> Permutation(String str) { c = str.toCharArray(); dfs(0); return res; } public void dfs(int x){ if(x == c.length-1) {res.add(new String(c)); return;} HashSet<Character> set = new HashSet<>(); for(int i=x;i<c.length;i++){ if(!set.contains(c[i])){ set.add(c[i]); swap(i,x); dfs(x+1); swap(i,x); } } } public void swap(int i, int j){ char temp = c[i]; c[i]=c[j]; c[j]=temp; } }