Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 81acc19

Browse files
authored
Create Permutations.java
1 parent 561b768 commit 81acc19

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎Backtracking/Permutations.java‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//LeetCode 46. Permutation
2+
//Question - https://leetcode.com/problems/permutations/
3+
4+
class Solution {
5+
public List<List<Integer>> permute(int[] nums) {
6+
List<List<Integer>> res = new ArrayList<>();
7+
boolean visit[] = new boolean[nums.length];
8+
9+
helper(nums, visit, new ArrayList<>(), res);
10+
return res;
11+
}
12+
13+
public void helper(int nums[], boolean visit[], List<Integer> perm, List<List<Integer>> res){
14+
//Base Case
15+
if(perm.size() == nums.length){
16+
res.add(new ArrayList<>(perm));
17+
return;
18+
}
19+
20+
for(int i = 0 ; i < nums.length ; i++){
21+
//Check if nums[i] is already in the current permutation or not
22+
if(visit[i]) continue;
23+
24+
//mark nums[i] as visited for the current permutation
25+
visit[i] = true;
26+
perm.add(nums[i]);
27+
28+
//generate the permutation further
29+
helper(nums, visit, perm, res);
30+
31+
//backtrack to generate new permutation
32+
visit[i] = false;
33+
perm.remove(perm.size()-1);
34+
}
35+
}
36+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /