classSolution{ public String getPermutation(int n, int k){ int[] nums = newint[n]; for (int i = 0; i < n; i++) { nums[i] = i + 1; } backtrace(nums, new StringBuilder(), k); return res.get(res.size() - 1); }
private List<String> res = new ArrayList<>(); privateboolean max = false;
publicvoidbacktrace(int[] nums, StringBuilder track, int k){ //结束条件 if (track.length() == nums.length) { res.add(track.toString()); if (res.size() == k) max = true; return; } for (int i = 0; i < nums.length; i++) { //剪枝 if (max) return ; if (track.indexOf(String.valueOf(nums[i])) != -1) continue; //做选择 track.append(nums[i]); //递归 backtrace(nums, track, k); //撤销 track.deleteCharAt(track.length() - 1); } } }
classSolution{ public String getPermutation(int n, int k){ int[] nums = newint[n]; for (int i = 0; i < n; i++) { nums[i] = i + 1; } backtrace2(nums, newboolean[n], new StringBuilder(), k); return res; }
private String res = ""; //优化一下空间,结果只存一个 privateint num = 0; publicvoidbacktrace2(int[] nums, boolean[] flag, StringBuilder track, int k){ //结束条件 if (track.length() == nums.length){ res = track.toString(); num++; return ; } for (int i = 0; i < nums.length; i++) { //剪枝 if (k == num) return ; if (flag[i]) continue; //做选择 track.append(nums[i]); flag[i] = true; //递归 backtrace2(nums, flag, track, k); //撤销 track.deleteCharAt(track.length() - 1); flag[i] = false; } } }