Problem_Permutation - xwu36/LeetCode GitHub Wiki
We need to find the next lexicographic permutation of the given list of numbers than the number formed by the given array. https://leetcode.com/problems/next-permutation/solution/
Explanation:
Now the main algorithm works in following steps -
I) Traverse the given number from rightmost digit,
keep traversing till you find a digit which is smaller than the previously traversed digit.
For example, if the input number is β534976β,
we stop at 4 because 4 is smaller than next digit 9.
If we do not find such a digit, then output is βNot Possibleβ.
II) Now search the right side of above found digit βdβ for the smallest digit greater than βdβ.
For β534976β³, the right side of 4 contains β976β.
The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to βdβ to the end of number.
The number that we get after sorting is the output.
For above example, we sort digits in bold 536974.
We get β536479β which is the next greater number for input 534976.
public class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
if (i >= 0) {
int j = nums.length - 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
private void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
public class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
dfs(nums, 0);
return res;
}
private void dfs(int[] arr, int sp){
if(sp == arr.length - 1){
List<Integer> tmp = new ArrayList<Integer>();
for(int num : arr) tmp.add(num);
res.add(tmp);
return;
}
for(int i = sp; i < arr.length; i++){
//if(i != sp && arr[i] == arr[sp])
//continue;
swap(arr, sp, i);
dfs(arr.clone(), sp + 1);
}
}
private void swap(int[] arr, int i, int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
Combination II, Subset II, Three Sum, Four Sum
if condition: if(i != sp && arr[i] == arr[i - 1]) continue;
class Main
{
// Print all subsets of given set[]
static void printSubsets(char set[])
{
int n = set.length;
// Run a loop for printing all 2^n
// subsets one by obe
for (int i = 0; i < (1<<n); i++)
{
System.out.print("{ ");
// Print current subset
for (int j = 0; j < n; j++)
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0)
System.out.print(set[j] + " ");
System.out.println("}");
}
}
// Driver code
public static void main(String[] args)
{
char set[] = {'a', 'b', 'c'};
printSubsets(set);
}
}