Algorithm/java tip
46. Permutations
개구리는 개꿀개꿀
2021. 3. 3. 17:51
leetcode.com/problems/permutations/submissions/
Permutations - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> tmp = new ArrayList();
backtrack(nums, ret, tmp);
return ret;
}
public void backtrack(int[] nums, List<List<Integer>> ret, List<Integer> tmp) {
// base case
if(tmp.size() == nums.length) {
ret.add(new ArrayList<Integer>(tmp));
return;
}
// recursion
for(int num:nums) {
if(tmp.contains(num)) continue;
tmp.add(num);
backtrack(nums, ret, tmp);
tmp.remove(tmp.size()-1);
}
}
}