Permutation of array

后端 未结 11 1192
我寻月下人不归
我寻月下人不归 2020-11-22 07:56

For example I have this array:

int a[] = new int[]{3,4,6,2,1};

I need list of all permutations such that if one is like this, {3,2,1

11条回答
  •  天涯浪人
    2020-11-22 08:20

    This a 2-permutation for a list wrapped in an iterator

    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    
    /* all permutations of two objects 
     * 
     * for ABC: AB AC BA BC CA CB
     * 
     * */
    public class ListPermutation implements Iterator {
    
        int index = 0;
        int current = 0;
        List list;
    
        public ListPermutation(List e) {
            list = e;
        }
    
        public boolean hasNext() {
            return !(index == list.size() - 1 && current == list.size() - 1);
        }
    
        public List next() {
            if(current == index) {
                current++;
            }
            if (current == list.size()) {
                current = 0;
                index++;
            }
            List output = new LinkedList();
            output.add(list.get(index));
            output.add(list.get(current));
            current++;
            return output;
        }
    
        public void remove() {
        }
    
    }
    

提交回复
热议问题